What is useEffect?
The ‘useEffect’ hook is a fundamental feature in React that handles the management of side effects within functional components. Side effects are actions such as data fetching, interacting with external APIs, and updating the DOM. These actions are critical for building a complex and dynamic application. “useEffect” allows developers to include side effect logic within a function that’s executed after the component renders. This function can also return a cleanup function that handles necessary cleanup tasks. “useEffect” provides a smooth way to integrate side effects, reduces the risk of memory leaks and enhances overall performance of the application.
Side Effects
A side effect is any effect that is responsible for changing the state of a component, when the state changes, the component re-renders. For example, accessing databases, fetching data from servers, updating the DOM, or subscribing to events. The useEffect helps isolate side effects from the rendering logic.
useEffect Dependencies
React’s “useEffect” dependencies allow control of when the side-effect runs. Dependencies is an optional array of variables, useEffect execute a callback function depending on if the dependencies have changed between each rendering.
Example
- This is the default case, there is no dependency array attach at the end. The call back function will executes every on single render.
- Passing an empty array as the second argument, the useEffect hook run the side effect once after the initial render. It would be useful in cases for fetching data from APIs and storing it just once.
- In this case, the state variable is passed into the dependency array, the side effect will run every time the value of the state variables updates.
You can add multiple state variables that influence the side effect.
- Similarly we can also use props to pass as dependency. The side effect runs every time there is a change to the props.
Cleanup
Cleaning up side effect is essential to the application's performance. To clean up the side effect, a function must be returned in the callback function we pass in the hook. The cleanup function gets invoked every time when the component unmount.






Top comments (1)
useEffect is not easy to get used to! Thanks for putting this guide together David. Also, welcome to dev.to!