useEffect:
- useEffect is one of the hooks concept in React.
- The useEffect Hook allows you to perform side effects in your components.
- Some examples of side effects are: fetching data, directly updating the DOM, and timers.
- useEffect accepts two arguments.
useEffect(<function>, <dependency>)
Syntax:
useEffect(() => {
// Code to run on each render
return () => {
// Cleanup function (optional)
};
}, [dependencies]);
Effect function: This is where your side effect code runs.
Cleanup function: This optional return function cleans up side effects like subscriptions or timers when the component unmounts.
Dependencies array: React re-runs the effect if any of the values in this array change.
Controlling side effects in useEffect:
1.No dependency passed:
To run useEffect on every render do not pass any dependency
useEffect(() => {
//Runs on every render
});
2.An empty array:
To run useEffect only once on the first render pass any empty array in the dependecy
useEffect(() => {
//Runs only on the first render
}, []);
3.dependency array:
To run useEffect on change of a particular value. Pass the state and props in the dependency array
useEffect(() => {
//Runs on the first render
//And any time any dependency value changes
}, [prop, state]);
Table:
| Type | When It Runs | Common Use Cases |
| ----------------------------- | -------------------------------- | ----------------------------- |
| `useEffect(() => {})` | After **every render** | General side effects |
| `useEffect(() => {}, [])` | **Only once** after first render | Fetch data, setup |
| `useEffect(() => {}, [a, b])` | When **`a` or `b` changes** | Sync with state/props changes |