useEffect and dependency Array
When an empty dependencies array ([]
) is passed to useEffect
, it ensures that the effect only runs once, after the initial render, and not on every render. This is a common pattern for running side effects that should only occur when the component mounts (e.g., fetching data, setting up subscriptions, etc.).
Here’s a detailed explanation:
useEffect with Empty Dependency Array
useEffect(() => {
// Effect code here
}, []);
Behavior
-
Initial Render:
- The effect runs after the initial render.
- This means the code inside
useEffect
is executed once when the component is first mounted.
-
Subsequent Renders:
- The effect does not run on subsequent renders.
- The empty array (
[]
) tells React that the effect does not depend on any values from props or state, so there’s no need to re-run the effect.
Example
Here’s an example demonstrating this behavior:
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
const App = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('useEffect called');
}, []); // Empty array as dependency
console.log('Rendering App');
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Output
-
On initial render, you will see:
Rendering App useEffect called
-
On subsequent renders (e.g., after clicking the "Increment" button), you will only see:
Rendering App
The useEffect
message appears only once after the initial render.
Comparison: No Dependency Array
If you omit the dependencies array, useEffect
runs after every render:
useEffect(() => {
console.log('useEffect called');
});
In this case, the effect runs after every render, meaning the message useEffect called
would appear every time the component re-renders, including when the "Increment" button is clicked.
Points to remember
- Empty Dependency Array (
[]
):useEffect
runs only once after the initial render. - No Dependency Array:
useEffect
runs after every render. - Specific Dependencies:
useEffect
runs after the initial render and whenever any of the specified dependencies change.