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 Counter Component with useState
Next, we need to create a new component that uses the useState hook to manage its state. 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 useEffect to Fetch Data
We can use the useEffect hook to fetch data from an API when our component mounts:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
{data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
export default DataFetcher;