Facebook Pixel
Step-by-Step Guide

How to Use the useEffect Hook in React

A step-by-step guide on how to run side effects in React components using useEffect with correct dependency arrays.

Understand What a Side Effect Is

A side effect is any operation that reaches outside the component's render cycle. This includes fetching data from an API, subscribing to events, setting up timers, manually updating the DOM, or reading from localStorage. These should not happen directly inside the render function.

Import and Call useEffect

Import useEffect from react and call it inside your component body. Pass it a callback function as the first argument. React will execute this callback after the component renders to the screen.

Understand the Dependency Array

The second argument to useEffect is the dependency array. This array controls when the effect runs. If you omit it entirely, the effect runs after every single render. If you pass an empty array, it runs only once after the first render. If you pass variables, it runs whenever any of those variables change.

Run an Effect Only Once on Mount

To run an effect only when the component first appears on screen, pass an empty array as the second argument. This is the correct way to trigger a one-time API call or set up a subscription when the component loads.

Run an Effect When Specific Values Change

If your effect depends on a prop or state variable, include that variable inside the dependency array. React will compare the previous and current values of every dependency after each render and re-run the effect only if at least one dependency has changed.

Return a Cleanup Function

If your effect sets up something that needs to be torn down, return a cleanup function from inside the useEffect callback. React calls this cleanup function before running the effect again and when the component unmounts. This prevents memory leaks from timers, subscriptions, or event listeners.

Never Call useEffect Conditionally

Do not place useEffect inside an if statement or a loop. Hooks must always be called in the same order on every render. If you need conditional behavior, put the condition inside the effect callback itself.

Avoid Missing Dependencies

Every variable from the component scope that is used inside the effect should be listed in the dependency array. Omitting dependencies can cause stale closures where the effect reads outdated values. ESLint's exhaustive-deps rule helps catch these mistakes automatically.

Ready to master this completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.