Search⌘ K
AI Features

Understanding useEffect Hook Design

Explore the useEffect hook to understand how React handles side effects in functional components. Learn to create, schedule, and clean up effects efficiently using dependency arrays and how React processes these effects during component lifecycles to optimize performance.

Overview of the useEffect hook

The useEffect hook in React is used to manage side effects in functional components. It allows us to perform tasks such as data fetching, DOM manipulation, etc.

The useEffect hook is used to set up a callback to be invoked after an update:

const Title = () => {
useEffect(() => {
// Code to be executed when the component mounts
window.title = "Hello World";
// Cleanup function to be executed when the component is unmounted
return () => {
window.title = "Notitle";
};
}, []); // Empty dependency array ensures the effect runs only on mount and unmount
};
Using useEffect hook to dynamically set and reset the window title

The useEffect function takes a callback function called create as its first input argument to define the effect. In the preceding example, the effect sets the window.title to be Hello World when the component is mounted.

A create function can return a function called destroy to perform the cleanup. The interesting thing here is that the destroy function is provided by the create function as a return value. In the preceding example, the cleanup returns the window.title object back to NoTitle when it is unmounted.

The second parameter in the useEffect argument list is a dependency array called deps. If deps is not given, the effect gets invoked each time during each update, whereas when deps is given, the effect only gets invoked upon a change from the deps array.

...