The useEffect Hook in React allows you to perform side effects in your function components. Side effects are operations that can affect other components and cannot be done during rendering. Common examples include fetching data, directly interacting with the DOM, setting up subscriptions, and more.
How Does useEffect Work?
The useEffect function takes two arguments:
A function that contains the code for the side effect.
An optional dependency array which controls when the effect runs.
The side effect function can optionally return a cleanup function. This cleanup function is called before:
The component unmounts, to free up resources.
The effect re-runs, which happens if any values in the dependency array have changed.
Dependency Array
The dependency array is a crucial feature of useEffect. It determines when the useEffect callback should be executed:
No dependency array: The effect runs after every rendering.
Empty dependency array ([]): The effect runs once after the initial render (similar to componentDidMount in class components).
Array with dependencies: The effect runs after the initial render and after every re-render if (and only if) any value in the dependency array changes.
Common Uses of useEffect
Fetching Data
One common use case is fetching data from an API:
Subscriptions
useEffect is also useful for setting up and tearing down subscriptions:
Interacting with the DOM
You can use useEffect to perform direct DOM manipulations, which are typically done after the component renders:
Rules and Best Practices
Do not perform side effects directly in the body of the component: This could lead to performance issues and bugs.
Place useEffect at the top level in your component: Like other Hooks, useEffect should not be called conditionally or inside loops or nested functions.
Use multiple effects to separate concerns: Each effect should be responsible for a single feature or side effect.