DEV Community

David Yao
David Yao

Posted on

React - How to implement useEffect hook in your application

The useEffect hook is a powerful feature in React that allows you to synchronize a component with an external system. It is a hook that lets you tell React what to do after render.

Here is a basic example that demonstrates how to use the useEffect hook:

 import React, { useState, useEffect } from 'react';

const Example = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default Example;

In this example, we are using the useState hook to manage the state of our component. The state count is set to 0 initially.

We then use the useEffect hook to update the document title whenever the count changes. The useEffect hook takes two arguments: a callback function and an array of dependencies. The callback function is the code that we want to run after render, and the array of dependencies is a list of values that we want to watch for changes. In this case, we only want to run the effect when count changes, so we pass [count] as the second argument.

Every time the component re-renders, React will compare the values in the dependency array to their previous values. If any of the values have changed, the effect will run again. If the values have not changed, the effect will not run. This is how React knows when to re-run an effect and when to skip it.

This is just a simple example, but you can use the useEffect hook to perform all sorts of complex logic in your React components, such as fetching data from an API, setting up and cleaning up subscriptions, and more.

USE CASES

Here are a few more examples to illustrate different use cases for the useEffect hook:

Fetching data from an API

 import React, { useState, useEffect } from 'react';

const Example = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(json => setData(json));
  }, []);

  return (
    <div>
      {data ? (
        data.map(post => (
          <div key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
          </div>
        ))
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};

export default Example;

Setting up and cleaning up a subscription

 import React, { useState, useEffect } from 'react';

const Example = () => {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return (
    <div>
      <p>Window width: {width}</p>
    </div>
  );
};

export default Example;

In this example, we are using the useEffect hook to set up and clean up a subscription to the resize event of the window object. The effect runs every time the component re-renders, but we don't need to do anything in the dependency array, because the effect does not depend on any values from props or state. The return value of the effect function is a cleanup function that removes the event listener when the component unmounts.

Updating a value based on a previous value

 import React, { useState, useEffect } from 'react';

const Example = () => {
  const [count, setCount] = useState(0);
  const [doubleCount, setDoubleCount] = useState(0);

  useEffect(() => {
    setDoubleCount(count * 2);
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Double Count: {doubleCount}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default Example;

In this example, we are using the useEffect hook to update a value doubleCount based on a previous value count. The effect runs whenever count changes, and we pass [count]

Happy coding! 😊

Latest comments (0)