What is useEffect in React, and is it bad to use it?

It’s a hook that runs after a component renders.

What does that mean?

It would be clear once you know how React displays a component.

Three stages of rendering

The three stages are: Trigger, Render, and Commit.

1. Trigger

A common trigger is page load.

React now needs to put the component on the screen.

So it’s time to render it.

2. Render

React components are functions.

Render means calling the function to return the HTML element.

For example, this component renders an image.

3. Commit

Finally, React adds the rendered elements to the DOM.

useEffect runs after commit.

It’s used for things that you can’t do during rendering.

Like an API call, or accessing the DOM.

But here’s the thing.

It’s tricky because it doesn’t only run once.

Dependency array & rerender

useEffect runs every time the component rerenders, which happens whenever there’s a state or props change.

React allows us to change that by adding an empty array as the second argument.

useEffect(()=> {
   //only runs on mount
}, [])

The useEffect will now only run once, when the component is first mounted.

But why do you sometimes see multiple items in the array?

useEffect(()=> {
   //runs on mount and items change
}, [item1, item2])

This is a list of items to help React decide whether to rerun the useEffect.

You aren’t supposed to choose the items here.

It depends on what you put in the useEffect.

The linter will tell you what to put here.

don’t useEffect

So why do developers hate useEffect?

Because it’s hard to debug and overused.

You will see it in every React codebase, and many of them are probably unnecessary.

Learning when to avoid useEffect is as important as learning how to use it.

Here are three common mistakes and how to fix them:

Updating state based on props or state

Don’t put things that can be calculated during rendering in an effect.

Caching expensive calculations

useEffect isn’t designed for caching.

Event-specific logic

Put event logic directly in the handler instead of setting state and triggering another useEffect.

Here, handleSubmit() is the handler and is triggered by a form submit.

Fee from Anime Coders

How did you like today's email?

Login or Subscribe to participate

Keep Reading

No posts found