Skip to main content

Command Palette

Search for a command to run...

Mastering the useEffect Hook: Synchronizing your React components with ease

Published
4 min read
Mastering the useEffect Hook: Synchronizing your React components with ease
U

I am a developer from Bangladesh. I love programming and circuits.

The useEffect hook is a powerful tool in React that allows you to synchronize a component with an external system. It can be used to fetch data from an API, add event listeners, or update the document title, among other things. In this blog post, I will show you how to use the useEffect hook to fetch data from an API and display it in a React component.

First, let's create a new React project using create-react-app.

npx create-react-app my-app
cd my-app

Next, let's create a new component called FetchData that will use the useEffect hook to fetch data from an API.

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

function FetchData() {
  const [data, setData] = useState(null);

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

  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 FetchData;

In the above code, we first import React, useState and useEffect hooks from the react library. Then we define our component called FetchData. In this component, we use useState to store the data that we fetch from the API and useEffect to fetch the data when the component is rendered.

The useEffect hook takes two arguments: a callback function and a list of dependencies. The callback function is called every time the component is rendered, and it is where we put the code to fetch the data from the API. The list of dependencies is an array of variables that, when changed, will cause the effect to run again. In this case, we pass an empty array, which means that the effect will only run once when the component is first rendered.

We use the fetch() function to get data from the API, https://jsonplaceholder.typicode.com/posts. We then use the .then() method to parse the response as json and then set the data in the state using setData(data).

In the JSX, we check whether the data is loaded or not, If the data is loaded we map over the data and display the title and body of each post, if the data is not loaded we display a loading message.

Finally, we export the component so that it can be imported and used in other parts of our application.

In the src/App.js file you have to import FetchData component and render it.

import React from 'react';
import FetchData from './FetchData';

function App() {
  return (
    <div>
      <FetchData />
    </div>
  );
}

export default App;

Now, if you run the application using npm start, you should see a list of posts fetched from the API and displayed on the page.

It's worth noting that the useEffect hook is not limited to fetching data from APIs. You can use it to perform any kind of side effect, such as adding event listeners, updating the document title, or setting up and tearing down a WebSocket connection.

Here's an example of how you can use the useEffect hook to add a click event listener to a button and update the document title:

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

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Example;

In this example, we use useState to keep track of the number of times the button is clicked. We use useEffect to update the document title with the current count. The second argument of the useEffect is the list of dependencies, and in this case, it is the count state. So, every time the count state updates, the effect will run and update the document title.

You can also use the useEffect hook to clean up any side effects that you set up. For example, if you use the useEffect hook to add an event listener, you can use it to remove the event listener when the component is unmounted. You can do this by returning a cleanup function from the useEffect callback.

In conclusion, the useEffect hook is a powerful tool that allows you to synchronize a component with an external system, whether it be a server, the browser, or another part of your application. It can be used for a wide variety of tasks, from fetching data to adding event listeners, and it provides a way to clean up any side effects that you set up. With the useEffect hook, you can handle side effects in a more elegant and controlled way in your functional components.