Using useState and useEffect in Functional Components

Tutorial 2 of 5

1. Introduction

This tutorial aims to introduce the useState and useEffect hooks in React and guide you through using them in functional components. By the end of the tutorial, you will be able to manage state and side effects in functional components effectively.

You will learn how to:
- Use the useState hook for state management in functional components.
- Use the useEffect hook for handling side effects in functional components.

Prerequisites:
- Basic knowledge of JavaScript and React.
- Understanding of functional components in React.

2. Step-by-Step Guide

React Hooks were introduced in React 16.8 to allow state and other React features to be used without writing a class. The two primary hooks you'll encounter are useState and useEffect.

useState

useState is a hook that lets you add React state to functional components.

Here's an example:

import React, { useState } from 'react';

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

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

export default Counter;

In this code, useState(0) declares a new state variable called count initialized with 0. setCount is the function we use to update the state. When the user clicks, the setCount function is called with the new count.

useEffect

useEffect is a hook that manages side effects in functional components. Side effects could be data fetching, subscriptions, or manually changing the DOM.

Here's an example:

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

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

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

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

export default Example;

In this code, useEffect is called after every render. When count changes, it updates the document title.

3. Code Examples

Example 1: Using useState

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>
  );
}

export default Example;

In this example, the button click updates the state of the count variable. The useState hook is used to define count as the state variable and setCount as the function to update this state. The initial state is set to 0.

Example 2: Using useEffect

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

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

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

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

export default Example;

In this example, we're using the useEffect hook to perform side effects in our component. The effect updates the document's title whenever the count state changes.

4. Summary

In this tutorial, we've covered how to use the useState and useEffect hooks in React functional components. You've learned how to manage state with useState and handle side effects with useEffect.

Next, you might want to learn about other hooks in React, such as useContext, useReducer, and useCallback. You can find more information in the React Hooks API Reference.

5. Practice Exercises

  1. Create a functional component with a state variable for the background color. Use the useState hook to change the background color when a button is clicked.

  2. Create a functional component with a counter. Use the useEffect hook to display an alert when the counter reaches a certain number.

  3. Create a functional component that fetches data from an API. Use the useState hook to store the data and the useEffect hook to fetch the data when the component mounts.

Remember to refer back to the examples and explanations in this tutorial as you work through these exercises. Happy coding!