useState
The useState hook is a built-in React function that allows you to add and manage local state within functional components. It tracks data that changes over time and automatically re-renders the component whenever that data is updated.
- useState is a React Hook that lets you add and manage state in a functional component.
Syntax
const [state, setState] = useState(initialValue);
state: The variable holding the current state value.
setState: The function used to update the state variable.
initialValue: The initial value given to the state variable during the first render. It can be a string, number, boolean, array, object, or null.
Example : Counter
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default Counter;
How it works
useState(0) initializes count to 0.
Clicking the button calls setCount(count + 1).
React updates count and re-renders the component.
The new value appears on the screen.
Updating State
setCount(count + 1);
Why use useState?
Without useState
let count = 0;
count++;
The UI won't update because React doesn't know the value changed.
With useState
const [count, setCount] = useState(0);
setCount(count + 1);
React knows the state changed and updates the UI automatically.
- useState stores data that changes over time.
- Calling the setter function (setState) triggers a re-render.
- Never modify state directly.
useEffect
The useEffect Hook is a built-in React function that lets you perform side effects in functional components. Side effects are operations that happen outside the normal rendering process, such as fetching data from an API, updating the document title, setting timers, or adding event listeners.
-
useEffectis a React Hook that lets you perform side effects in a functional component.
Syntax
useEffect(() => {
// Side effect code
}, [dependencies]);
- Callback Function: Contains the side effect code that React executes.
- Dependency Array: Controls when the effect should run. It is optional.
Example: Update Document Title
import { useState, useEffect } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default Counter;
How it works
-
useState(0)initializescountto0. - When the component renders for the first time,
useEffectruns after React updates the UI. - Clicking the button calls
setCount(count + 1). - React updates the
countvalue and re-renders the component. - Since
countchanged,useEffectruns again. - The browser tab title is updated with the latest count.
Updating Side Effects
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
Why use useEffect?
Without useEffect
document.title = `Count: ${count}`;
If you write this directly inside the component, it runs every time the component renders, even when it isn't necessary.
With useEffect
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
React runs the effect only when count changes, making your application more efficient.
-
useEffectis used to perform side effects after rendering. - It keeps side-effect code separate from rendering logic.
- The dependency array helps control when the effect should run.
Dependency Array
The dependency array decides when useEffect should execute.
1. No Dependency Array
useEffect(() => {
console.log("Runs after every render");
});
Output
- Runs after the initial render.
- Runs again after every re-render.
2. Empty Dependency Array
useEffect(() => {
console.log("Runs only once");
}, []);
Output
- Runs only once after the component is mounted.
- Commonly used for API calls or initial setup.
3. Dependency Array with Values
useEffect(() => {
console.log("Count changed");
}, [count]);
Output
- Runs after the first render.
- Runs again only when
countchanges. - Does not run when other state variables change.
Cleanup Function
Some side effects continue running even after a component is removed. A cleanup function allows React to remove those side effects.
import { useEffect } from "react";
function Timer() {
useEffect(() => {
const timer = setInterval(() => {
console.log("Running...");
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return <h1>Timer Started</h1>;
}
export default Timer;
How it works
-
setInterval()starts a timer. - The cleanup function is returned from
useEffect. - React calls the cleanup function before the component unmounts.
-
clearInterval()stops the timer and prevents memory leaks.
Common Uses of useEffect
- Fetch data from an API.
- Update the document title.
- Start and stop timers.
- Add and remove event listeners.
NOTE
-
useEffectis used for performing side effects. - It runs after React renders the component.
- The dependency array controls when the effect runs.
- A cleanup function removes side effects when they are no longer needed.
-
useEffecthelps keep your components clean, organized, and efficient.
The useState Hook is used to create and manage state in React functional components, allowing the UI to update whenever the state changes. The useEffect Hook is used to perform side effects such as fetching data, updating the document title, or working with timers after a component renders. Together, these Hooks form the foundation of modern React development, helping you build dynamic, interactive, and maintainable applications.
References
https://www.geeksforgeeks.org/reactjs/reactjs-usestate-hook/
https://www.geeksforgeeks.org/reactjs/reactjs-useeffect-hook/
https://www.w3schools.com/react/react_usestate.asp
https://www.w3schools.com/react/react_useeffect.asp
Top comments (0)