Share:
Hi,
I’m working on a React project and I’m struggling to manage state effectively. Can someone explain how to use React Hooks, specifically useState and useEffect, to manage state in a functional component? Examples would be great!
Hide Responses
Hi,
To manage state in React using Hooks:
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>
);
}
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));
}, []); // Empty array means this effect runs once
return (
<div>
{data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => setData(data));
}, [url]);
return data;
}
function DataComponent() {
const data = useFetch('https://api.example.com/data');
return (
<div>
{data && data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
These hooks help manage state and side effects efficiently in React.
William Turner
9 months ago