useState & useEffect 🪝 from counter to data fetching!

useState & useEffect 🪝 from counter to data fetching!

[Beginner Friendly]

Introduction to useState and useEffect in React

useState and useEffect are two of the most commonly used Hooks in React. They allow you to add state and side effects to functional components, which were previously only possible with class-based components.

What are Hooks?

Hooks are a way to add state and other React features to functional components. Before the introduction of Hooks, the only way to add state and lifecycle methods to a component was to use a class-based component. However, with Hooks, you can add state and side effects to functional components as well, making them a powerful tool for building React applications.

What is useState?

useState is a Hook that allows you to add state to a functional component. It takes a single argument, which is the initial state, and returns an array with two elements: the current state and a function that allows you to update the state.

Here's an example of how to use useState to add a count to a functional component:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

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

In this example, we declare a new state variable called count using useState, and set its initial value to 0. The useState function returns an array with two elements: the current value of count and a function called setCount that allows us to update the value of count.

We can then use the count variable in our component to display the current count, and the setCount function to update the count when the button is clicked.

What is useEffect?

useEffect is a Hook that allows you to perform side effects in a functional component. It takes a function as an argument, which will be called after the component is rendered. This function is known as an "effect".

Here's an example of how to use useEffect to log a message when the component is rendered:

import React, { useEffect } from 'react';

function Example() {
  useEffect(() => {
    console.log('The component has rendered');
  });

  return <div>Hello, world!</div>;
}

In this example, we use useEffect to define an effect that will log a message to the console when the component is rendered. The effect function will be called after the component is rendered, and will run every time the component is re-rendered.

Data Fetching with useEffect

One of the most common uses for useEffect is to fetch data from an API. Here's an example of how to use useEffect to fetch data from the GitHub REST API

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

function Example() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('https://api.github.com/users/thatbeautifuldream');
      const data = await response.json();
      setData(data);
      setLoading(false);
    }

    fetchData();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <p>Name: {data.name}</p>
      <p>Location: {data.location}</p>
      <p>Bio: {data.bio}</p>
    </div>
  );
}

In this example, we use useState to declare two state variables: data and loading. We set the initial value of data to null and the initial value of loading to true.

We then use useEffect to fetch data from the GitHub API. The effect function makes an API call using the fetch function, and then updates the state using the setData and setLoading functions.

We pass an empty array as the second argument to useEffect, which tells React to only run the effect when the component is initially rendered. This is important, because we don't want to fetch the data every time the component is re-rendered.

Finally, we use the loading state variable to display a "Loading..." message while the data is being fetched, and then display the data when it's available.

Conclusion

useState and useEffect are two powerful Hooks that allow you to add state and side effects to functional components in React. They are easy to use and can greatly simplify your code, making them an essential part of any React developer's toolkit.

Did you find this article valuable?

Support Milind Mishra by becoming a sponsor. Any amount is appreciated!