React useEffect and useState — Easy Guide

Asiful Alam Fahim
By Asiful Alam Fahim
July 0, 2023

React useEffect and useState — Easy Guide

Hey there, fellow React lovers! Have you ever wondered how to make your React components more awesome and dynamic? Well, you’re in luck, because today we’re going to learn about React hooks!

Photo by Lautaro Andreani on Unsplash

React hooks are a cool feature that lets you use state and other React goodies without writing a class. They make your code shorter, cleaner, and more reusable. In this guide, we will focus on two of the most popular hooks: useState and useEffect.

useState is a hook that lets you store values between function calls and is similar to this.state in a class. You can use it to keep track of any kind of data, such as text, numbers, lists, objects, etc.

On the other hand, useEffect lets you do stuff in function components and can be thought of as a mix of componentDidMount, componentDidUpdate, and componentWillUnmount in a class. You can use it to get data from an API, change the document title, listen to events, etc.

But why should you use these hooks? And when should you use them? Well, let me tell you!

You should use useState when you want to store some data that changes over time in your component. And for useEffect, you should use it when you want to do something after your component renders or updates.

Using these hooks will make your code more functional and declarative, which means that you can focus on what your component does rather than how it does it. This will make your code easier to understand and maintain.

Sounds good? Great! Let’s dive into some examples and see how to use these hooks in action!

useState Example: A Counter

Let’s start with a simple example of using useState to create a counter component that shows the number of clicks and has a button to increase it by one.

First, we need to import the useState hook from React:

import { useState } from "react";

Then, we need to create a state variable and a function to update it inside our component. We can use the destructuring assignment syntax to give them names. We also need to pass an initial value to the useState hook, which in this case is 0:

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

Next, we need to return some JSX that displays the count value and the button element. We can use curly braces to insert JavaScript expressions inside JSX. We also need to add an onClick handler to the button that calls the setCount function with the new value:

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

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

That’s it! We have created a functional component that uses state with the useState hook.

Pretty cool, right? But how does it work? Let me explain!

When we call the useState hook with an initial value of 0, it returns an array with two elements: the current state value (count) and a function to update it (setCount). We use the destructuring assignment syntax to assign them names.

Then, we return some JSX that renders the count value and the button element. When we click the button, we call the setCount function with the new value (count + 1). This updates the state variable and triggers a re-render of the component. As a result, we see the updated count value on the screen.

This way, we can store and update any kind of data in our component using the useState hook. It’s like magic!

useEffect Example: Fetching Data

Now let’s see how to use useEffect to fetch some data from an API and display it in our component. For this example, we will use the JSON Placeholder API that provides some fake data for testing purposes.

First, we need to import the useEffect hook from React, along with the useState hook:

import { useState, useEffect } from "react";

Then, we need to create a state variable and a function to update it for storing the data that we will fetch from the API. We will initialize it with null since we don’t have any data yet:

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

Next, we need to use the useEffect hook to fetch the data when the component mounts. The useEffect hook takes two arguments: a callback function that performs the side effect, and an optional array of dependencies that determines when the effect should run. If we pass an empty array as the second argument, the effect will only run once after the initial render:

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

useEffect(() => {
// fetch data here
}, []);
}

Inside the callback function, we can use the fetch API or any other library to make an HTTP request to the API endpoint. For simplicity, we will use fetch here. The fetch API returns a promise that resolves to a response object. We need to call the json() method on the response object to get the actual data as JSON. Then, we need to call the setData function with the data as an argument to update our state variable:

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

useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => setData(data))
.catch((error) => console.error(error));
}, []);
}

Finally, we need to return some JSX that renders the data in our component. We can use conditional rendering to check if the data is null or not. If it is null, we can show a loading message. If it is not null, we can map over the data array and display each item as a list:

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

useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => setData(data))
.catch((error) => console.error(error));
}, []);
return (
<div>
{data ? (
<ul>
{data.map((item) => (
<li key={item.id}>
{item.name} - {item.email}
</li>
))}
</ul>
) : (
<p>Loading...</p>
)}
</div>
);
}

And that’s it! Let me explain this too…

When we call the useEffect hook with a callback function and an empty array, it runs the callback function once after the initial render. Inside the callback function, we make a fetch request to the API and get the data as JSON. Then, we call the setData function with the data as an argument to update our state variable. This triggers a re-render of the component and shows the data on the screen.

The useEffect hook also cleans up after itself when the component unmounts. This means that it cancels any pending requests or subscriptions that are no longer needed. This prevents memory leaks and unwanted behavior.

Through this process, we can do anything that needs to happen after our component renders or updates using the useEffect hook.

Wrap-Up

In this guide, we have learned how to use two important React hooks: useState and useEffect. We have seen how to use useState to create and update state variables in functional components, and how to use useEffect to do stuff after our component renders or updates. We have also seen how to use conditional rendering and array methods to display the data in our components.

React hooks are a powerful and elegant way to write React components. They let us use state and other React goodies without writing a class, and they make our code shorter, cleaner, and more reusable. There are many other hooks that React provides, such as useRef, useMemo, useCallback, etc. You can learn more about them from the official React documentation.

I hope you enjoyed this guide and learned something new. If you have any questions or feedback, please let me know in the comments below. Happy coding!

I hope this article has been helpful for you. Thank you for taking the time to read it.

Get an email whenever Asiful Alam Fahim publishes.

If you’re interested in more in-depth and technical write-ups like this one, be sure to follow me on Medium. And for all things related to startups, business, or web development, connect with me on LinkedIn.

Ready to design and develop your custom website? Please don’t hesitate to contact me! I’m always here to answer your questions and help bring your vision to life. To keep the inspiration flowing, check out the below articles I’ve written. Together, let’s continue to grow and expand our knowledge!

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.


React useEffect and useState — Easy Guide was originally published in JavaScript in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.

  Back

Follow Me