How to use the ReactJS useEffect hook

Key takeaways:

  • The useEffect Hook enables you to perform side effects such as data fetching, DOM updates, and event handling in functional components.

  • By specifying dependencies in useEffect, you can control exactly when the effect should run (on mount, state updates, or unmount, etc.).

  • The useEffect Hook is ideal for data fetching from APIs, manipulating the DOM, managing timers, and handling browser events like window resizing.

The useEffect Hook

The useEffect Hook is one of React’s built-in Hooks that allows you to perform side effects in React functional components when the application mounts or when the state or prop gets updated. A side effect could include:

  • Data fetching from an external API.

  • Manipulating the Document Object Model (DOM).

  • Using a timer function like setTimeout() that runs for a certain period.

Before Hooks, you would have been required to use class components to handle life cycle methods like componentDidMount and componentDidUpdate. The useEffect hook replaces those life cycle methods and provides a cleaner, simpler way to manage side effects in functional components.

Practice the useEffect hook with hands-on experience with this project: Build a Memory Game Using React.

Rules when using Hooks

  • You should call Hooks only at the top level of the component, meaning they should not be called inside loops, conditions, or nested functions.

  • You should call Hooks only in React functional components or within custom Hooks. Hooks won’t work in class components or regular JavaScript functions outside the React environment.

Note: The above rules should not be regarded as the use case for only useEffect, but for any Hook you decide to use, even custom hooks.

Syntax for the useEffect Hook

The syntax to define the useEffect Hook is as follows:

useEffect(callbackFunction, [dependencies]);
Syntax for the useEffect hook

In the syntax above, we have the following:

  • A callback function, callbackFunction, contains the logic that will run when the component renders or updates.

  • An optional dependency array, [dependencies]. This array determines when the effect should be re-run. If it’s empty, the effect runs only once on the component mount. If state or props are listed, the effect runs whenever they change.

Note: The dependency array is optional, but how you use it drastically affects how your component behaves. For example:

  • If you provide an empty dependency array, [], then the effect only runs once on the component’s initial render.

  • If specific dependencies, [dependency1, dependency2], are provided then the effect runs only when a value in the dependency array changes.

  • If no dependency array is provided then the effect will run after every render.

Example 1: useEffect with an empty dependency array

In the example below, an empty array [] ensures the effect only runs once when the component is mounted. This use case is useful for initializing data, such as fetching user info on load. You will see Component mounted! only once in the console.

Explore the useEffect Hook by implementing it in a real world use case in this project: Build the Frontend of a Financial Application Using React.

Example 2: useEffect with specific dependencies

In the example below, the effect will only run when the items state changes. The dependency array [items] ensures the effect doesn’t run on every render but only when items updates. Changes to the price state do not trigger the effect because price is not included in the dependency array.

On the initial render, the useEffect logs Number of items changed to: 0. Each time the user clicks the “Increase Items” button, the items state changes, causing a rerender and triggering the effect.

Example 3: useEffect with no dependency array

In the example below, no dependency array is provided, therefore, the effect will execute every time the component renders. This includes both initial render and subsequent re-renders triggered by state updates.

Initially, "Component rendered!" is logged when the component mounts. Every time you click the “Increase Items” or “Increase Price” buttons, the states change, causing a rerender. The useEffect runs again after each rerender, logging the message to the console.

Apply the useEffect hook in a real-world scenario by working on this project: Build an Image Sharing App with MERN Stack.

Example 4: Fetching data with useEffect

Let’s look at a simple example of how to fetch data from an API when the component mounts using the useEffect Hook. We initialize a local state, posts, as an empty array and then define the useEffect Hook so that it executes after the component mounts. We then use the fetch API to fetch posts from an API and finally convert the API response to JSON. We then update the posts state with the fetched data.

Conclusion

The useEffect Hook simplifies side effect management in React’s functional components. It provides a clean, unified way to handle API requests, DOM manipulation, timers, and event listeners. By using the dependency array, you can gain fine-grained control over when the effect should run.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


When should I use the useEffect Hook?

Use the useEffect Hook whenever you need to perform side effects such as data fetching, DOM updation etc.


What is the difference between useEffect and life cycle methods?

The useEffect hook serves as a replacement for life cycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components, offering a more unified and flexible way to manage side effects. Unlike life cycle methods, which are tied to specific phases, useEffect can run after every render or only when certain dependencies change, based on the dependency array provided.

It also allows multiple effects within a single component, promoting cleaner separation of logic. Additionally, the return function inside useEffect handles cleanup tasks, acting similarly to componentWillUnmount. This consolidated approach simplifies the code and provides more control over when and how side effects are executed.


Can I use multiple useEffect Hooks in a component?

Yes, you can call useEffect multiple times in a component, each handling a different side effect.


What happens if I don’t use a dependency array?

If you do not use a dependency array, then the effect will run on every render. This can lead to performance issues in the application.


Free Resources