Follow me on LinkedIn
Follow me on Github.com
Friends
Understanding these hooks is crucial for managing state and side effects in your React applications. They provide a powerful way to build dynamic and responsive UIs with functional components.
useState
The useState hook allows you to add state to functional components. Here's a simple example demonstrating how to use useState:
Counter Example
import React, { useState } from 'react';
function Counter() {
// Declare a state variable named "count" and a function "setCount" to update it
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 example:
-
useState(0)initializes thecountstate variable with0. -
setCountis a function that updates the state. - Clicking the button increments the
countstate by 1, which causes the component to re-render and display the new count.
useEffect
The useEffect hook allows you to perform side effects in function components. Side effects can include data fetching, subscriptions, or manually changing the DOM.
Example: Data Fetching
Here's an example that uses useEffect to fetch data from an API when the component mounts:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Fetch data from an API
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
});
}, []); // Empty dependency array means this effect runs once after initial render
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<h1>Fetched Data</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
}
export default DataFetcher;
In this example:
-
useEffectis used to fetch data when the component mounts. - The empty dependency array (
[]) ensures that the effect runs only once after the initial render. - The fetched data is stored in the
datastate variable, and theloadingstate variable is used to show a loading message until the data is fetched.
useEffect Dependencies
The useEffect hook can also accept a dependency array that allows you to control when the effect runs.
Example: Effect with Dependencies
import React, { useState, useEffect } from 'react';
function CounterWithEffect() {
const [count, setCount] = useState(0);
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
// Clean up by resetting the title when component unmounts
return () => {
document.title = 'React App';
};
}, [count]); // Only re-run the effect if count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default CounterWithEffect;
In this example:
- The effect updates the document title whenever the
countstate changes. - The dependency array
[count]ensures that the effect only runs whencountchanges. - The cleanup function resets the document title when the component unmounts or before the effect runs again.
Conclusion
- useState is used for adding state to function components. It returns an array containing the current state value and a function to update it.
- useEffect is used for handling side effects in function components. It runs after the component renders and can optionally clean up before the component unmounts or before the effect runs again.
Happy Coding !
Top comments (0)