Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active April 15, 2025 23:04
Show Gist options
  • Select an option

  • Save wilmoore/b95955a72f96b4862d68086dfe9c8501 to your computer and use it in GitHub Desktop.

Select an option

Save wilmoore/b95955a72f96b4862d68086dfe9c8501 to your computer and use it in GitHub Desktop.
Software Engineering :: Programming :: Languages :: JavaScript :: ReactJS :: Hooks :: useEffect

Software Engineering :: Programming :: Languages :: JavaScript :: ReactJS :: Hooks :: useEffect

⪼ Made with 💜 by Polyglot.

useEffect is not for all effects. The mental model is synchronization. Not lifecycle.

image

In React, side effects usually belong inside event handlers. Event handlers are functions that React runs when you perform some action—for example, when you click a button. Even though event handlers are defined inside your component, they don’t run during rendering! So event handlers don’t need to be pure.

If you’ve exhausted all other options and can’t find the right event handler for your side effect, you can still attach it to your returned JSX with a useEffect call in your component. This tells React to execute it later, after rendering, when side effects are allowed. However, this approach should be your last resort.

You Might Not Need an Effect

A setState inside of a useEffect should be kind of a warning...

image

Infinite Loops

By default, Effects run after every render. This is why code like this will produce an infinite loop:

const [count, setCount] = useState(0);
useEffect(() => setCount(count + 1));

Effects run as a result of render. Setting state triggers rendering. Setting state immediately in an Effect is like plugging a power outlet into itself. The Effect runs, it sets the state, which causes a re-render, which causes the Effect to run, it sets the state again, this causes another re-render, and so on.

Effects should usually synchronize your components with an external system. If there's no external system and you only want to adjust some state based on other state, you might not need an Effect.

  • Race Conditions
  • No Instant Back Button
  • No initial HTML Content
  • Chasing Waterfalls

useEffect

The function (effect) passed runs on mount and on update (re-render). With a

Run On Initial Load (empty array)

useEffect(() => {}, [])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment