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.
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.
A
setStateinside of auseEffectshould be kind of a warning...
- You Might Not Need an Effect
- All 12 useState & useEffect Mistakes Junior React Developers Still Make in 2023
- Why I avoid useEffect For API Calls and use React Query instead
- Keeping Components Pure
- Replaces
componentDidMount,componentDidUpdate,componentWillUnmount - React 18 runs effects twice on mount (in strict mode)
- You should Avoid these React useEffect Mistakes
- useEffect is not a lifecycle hook
- Fetching in useEffect problems
- You don't need useEffect for transforming data
- setState within useEffect is a red flag
- You don't need useEffect for communicating with parents
- You don't need useEffect for subscribing to external stores
- You don't need useEffect for initializing global singletons
- You don't need useEffect for handling user events: use an event handler, extract to a custom hook and consider using something like stately and XState
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
The function (effect) passed runs on mount and on update (re-render). With a
- useEffect
- Using the Effect Hook
- Goodbye, useEffect - David Khourshid
- A complete guide to the useEffect React Hook
- A Visual Guide to useEffect
- What's useEffect execution order and its internal clean-up logic in react hooks?
Run On Initial Load (empty array)
useEffect(() => {}, [])


