React.js / React Hooks

Using useState and useEffect in Functional Components

In this tutorial, we will explore two primary React Hooks, useState and useEffect. You will learn how to manage state and side effects in functional components using these hooks.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Introduces React hooks for functional components to manage state and side effects.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Age Calculator

Calculate age from date of birth.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help