Blog Details
Tajul Islam Refath
10 Oct 2024
8 min read
React Hooks are special functions introduced in React to make managing states and side effects easier within functional components. Before hooks, only class components could manage state and lifecycle methods. Hooks changed that by allowing functional components to handle the same tasks, making the code cleaner and more reusable.
Hooks like useState
and useEffect
are two of the most commonly used hooks. They let you manage the state of your app and run code when certain things happen, like when the component first renders or when data changes.
The useState
hook allows you to add state to functional components. With it, you can keep track of variables that can change as your component runs, like form inputs or counters.
How useState
Works:
Here’s an example:
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>
);
}
In this example:
useState(0)
initializes the count
state with a value of 0.setCount
updates the count
state when the button is clicked.Whenever the state changes, the component re-renders with the new value, making it easy to handle dynamic data.
The useEffect
hook is used to handle side effects in React components. Side effects are actions that affect something outside the component, like fetching data from an API, updating the DOM, or setting up timers. It runs code after a render or when certain data changes.
How useEffect
Works:
Here’s an example:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(result => setData(result));
}, []); // Empty array ensures it only runs once after the first render.
return (
<div>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
In this example:
useEffect
is fetching data from an API after the component renders.[]
makes sure the effect only runs once, similar to componentDidMount
in class components.[count]
, the effect would re-run whenever count
changes.
React hooks have dramatically changed how we build applications in React by allowing developers to use state, side effects, and other advanced features in functional components. They encourage code reuse and promote cleaner, more efficient code. By mastering these hooks, you'll become more adept at building modern, scalable React applications.
Let’s build a small interactive example using both useState
and useEffect
:
useEffect
to log a message to the console every time the count changes.import React, { useState, useEffect } from 'react';
function CounterWithEffect() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`You clicked ${count} times`);
}, [count]); // Logs message whenever 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:
useState
is used to track the count
.useEffect
is used to log the count value to the console every time the button is clicked.This demonstrates how easily you can manage both state and side effects in React using hooks. You don’t need class components or lifecycle methods anymore!
Don’t worry, we don’t spam!