DEV Community

A.Esakki Muthu
A.Esakki Muthu

Posted on

React useState and useEffect

  1. useState Definition

useState is a React Hook used to store and manage changing data in a component.

Purpose

We use useState when a value can change and we want React to update the UI when that value changes.

Example
const [count, setCount] = useState(0);

Here:

count → current value
setCount → changes the value
0 → initial value

If we click a button:

setCount(count + 1);

The value changes:

0 → 1 → 2 → 3

And React updates the screen.

Where can we use it?

useState is commonly used for:

Counter
Input fields
ON/OFF buttons
Show/Hide
Login status
Shopping cart
Search text
Easy memory

useState = Store changing data + update the UI


  1. useEffect Definition

useEffect is a React Hook used to run some code after a component renders or when a particular value changes.

Purpose

We use useEffect when we need to perform an action based on rendering or changes in data.

For example:

Fetch data from an API
Start a timer
Change the browser title
Listen for events
Work with external systems
Example
useEffect(() => {
console.log("Component rendered");
}, []);

The code inside useEffect runs after the component renders.

What is []?
useEffect(() => {
console.log("Hello");
}, []);

The empty [] means the effect runs after the initial render.

If we use:

useEffect(() => {
console.log("Count changed");
}, [count]);

The effect runs when count changes.

useState → "What data should I store?"

useEffect → "What code should I run after rendering or when something changes?"

Top comments (0)