BeginnerCoder
intermediate#react#hooks#state management

Using React Hooks to Manage State

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to use React Hooks to manage state in functional components, including the useState and useEffect hooks.

Introduction to React Hooks

In this tutorial, we will learn how to use React Hooks to manage state in functional components. We will cover the useState and useEffect hooks.

Step 1: Setting Up the Project

First, we need to set up a new React project. We can do this by running the following command in our terminal:

npx create-react-app hooks-app

Step 2: Creating a Functional Component

Next, we need to create a new functional component. We can do this by creating a new file called Counter.js in the src directory:

import React, { useState } from 'react';

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

return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
}

export default Counter;

Step 3: Using the useEffect Hook

To use the useEffect hook, we can add it to our Counter.js file:

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

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

useEffect(() => {
        document.title = `Count: ${count}`;
    }, [count]);

return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
}

export default Counter;
Keep going with react

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.