In React.js, the `useEffect` hook is used to perform side effects in functional components. When using `useEffect`, we can provide a dependency array as the second argument to control when the effect should run.
The dependency array is an optional parameter that contains variables or values that the effect depends on. React will re-run the effect whenever any of the dependencies change. If the dependency array is empty, the effect will only run once after the initial render.
Example:
import React, { useState, useEffect } from 'react';
function ExampleComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
// This effect will run after every render
console.log('Effect ran');
});
useEffect(() => {
// This effect will only run once after the initial render
console.log('Initial effect ran');
}, []);
useEffect(() => {
// This effect will run whenever the 'count' state changes
console.log('Count changed:', count);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default ExampleComponent;
In this example:
- The first `useEffect` hook has no dependencies, so it will run after every render.
- The second `useEffect` hook has an empty dependency array, so it will only run once after the initial render.
- The third `useEffect` hook depends on the `count` state variable, so it will run whenever `count` changes.
By specifying dependencies in the dependency array, we can control when the effect should run, optimizing performance and preventing unnecessary re-renders.