intermediate#react#hooks#state management
Using React Hooks to Manage State
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;