Side effects and cleaning with useEffect
The useEffect
is a Hook that allows handling side effects in functional components. Side effects include tasks like fetching data, updating the DOM, and setting up subscriptions. Let’s explore how to use useEffect
clearly and efficiently.
Understanding useEffect
The useEffect
accepts two arguments. The first is a function where we place the side effect code. The second is a dependency array. Let’s look at a basic example:
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
document.title = 'Hello, world!';
});
return <div>Check out the page title!</div>;
}
In this example, the page title changes to “Hello, world!” when the component is rendered.
useEffect Dependencies
The dependency array allows you to control when the effect is executed. If you want the effect to run only once, pass an empty array:
useEffect(() => {
console.log('Component mounted');
}, []);
If you want the effect to run when a specific variable changes, include it in the array:
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`You clicked ${count} times`);
}, [count]);
In this case, the effect runs every time count
changes.
Cleaning up with useEffect
Some side effects need to be cleaned up to avoid issues like memory leaks. The function passed to useEffect
can return a cleanup function. Let’s look at an example with a timer:
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => clearInterval(timer);
}, []);
Here, the timer is created when the component is mounted and cleaned up when the component is unmounted.
Summary
The useEffect
is a powerful Hook for handling side effects in functional components. It helps execute code after rendering and clean up resources when necessary.
Use it to fetch data, update the DOM, and set up subscriptions, always paying attention to dependencies and effect cleanup. With practice, you will master the use of useEffect
in your React applications.