Menu

Understanding useState in React: Why Re-render Happens
🖼️

Understanding useState in React: Why Re-render Happens

DEV Community: tutorial·Jayashree·5 months ago
#XdlyB8Xw
#dev#count#react#usestate#state
Reading 0:00
15s threshold

When learning React, one common question is:

“If state changes, does React re-render?”

The answer is yes .

To understand this, first we need to know what useState does.

What is useState?

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

Example:

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

Here:

count -> stores the current value

setCount -> updates the value

0 -> initial value

Initially:

count = 0

React renders the UI and displays:

0

What Happens When State Changes?

Consider this counter example :

import { useState } from " react " ;

function Counter () {

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

return (

<> < h1 > { count } </ h1 >

< button onClick = { () => setCount ( count + 1 ) } >

Increment

</ button >

</>

);

}

export default Counter ;

Enter fullscreen mode

Exit fullscreen mode

When the button is clicked:

setCount(count + 1)

React updates the state.

Flow:

Button Click

↓

State Changes

↓

Component Re-renders

↓

Updated UI Appears

Enter…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.