In React, useEffect and useState
2024
In React, useEffect
and useState
are two of the most commonly used hooks, each serving different purposes in managing component behavior and state.
1. useState:
useState
is a hook that allows you to create and manage state in functional components.
Usage:
- Initialize State: You pass the initial state value to
useState
. - Read State: It returns a state variable, which you can read at any time.
- Update State: It provides a function that allows you to update the state and re-render the component.
Example:
import { useState } from 'react';
function Counter() {
// Declare a state variable `count` and a function `setCount` to update it
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
- Initial State:
useState(0)
initializes thecount
to0
. - Updating State: When the button is clicked,
setCount
updates thecount
state, causing the component to re-render with the new value.
2. useEffect:
useEffect
is a hook that lets you perform side effects in functional components. Side effects include things like data fetching, subscriptions, DOM manipulation, timers, etc.
Usage:
- Run Effects: It runs after the component renders or updates.
- Dependencies: You can control when it runs by specifying dependencies (e.g., run only when certain state variables change).
Example:
import { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
// Effect: Fetch data from an API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty array as dependency means it runs only on mount (componentDidMount equivalent)
return (
<div>
{data ? <p>Data: {JSON.stringify(data)}</p> : <p>Loading...</p>}
</div>
);
}
- Effect Logic: The function inside
useEffect
will run after the component renders, which is used here to fetch data. - Dependencies:
[]
means the effect runs only on the initial render (component mount), similar tocomponentDidMount
in class components.
Key Features:
- No Dependencies: If you omit the dependency array, the effect will run after every render.
- With Dependencies: You can pass specific state or props in the array to only trigger the effect when those values change.
- Cleanup: You can return a cleanup function inside
useEffect
to run logic when the component unmounts or before the effect runs again.
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => {
clearInterval(timer); // Cleanup on unmount or before rerunning the effect
};
}, []);
Differences:
Feature | useState | useEffect |
---|---|---|
Purpose | Holds state values in a functional component | Handles side effects (e.g., data fetching, subscriptions) |
Triggers Re-render | Yes, when state is updated with the setter function | No, it runs after render but does not trigger re-renders itself |
Usage | To track and update values that affect rendering | To perform actions based on component lifecycle or state changes |
Runs | Initializes on component mount and updates state as needed | Runs after every render, or when specific dependencies change |
Examples | Counter, form inputs, toggle switches | Fetching data, API calls, timers, subscriptions |
Summary:
useState
is for managing state (i.e., data that changes over time).useEffect
is for performing side effects (i.e., actions outside the React component rendering, such as API calls, setting up subscriptions, etc.).
They are often used together in applications, where useEffect
performs some operation that updates the state with useState
.