Skip to content

ReactJS -- If it is setting a state with the same value, will the component be re-rendered?

github logo ・1 min read  

Function component -- setValue(v)

if v is the same value as before, then the function component won't be re-rendered (the function component won't be called).


Class component -- setState({ data: v })

if v is the same value as before, then the class component will be re-rendered (the class component's render() will be called).


twitter logo DISCUSS (9)
markdown guide

While your state of the function component is just a primitive value, the class component uses an object. In your class component, the value does not change but the state itself does, you get a new object. That's why it rerenders even if the value has not changed.

Change your function component to an object and you will get the same result (no, I don't say that you should do that in real projects):

const [state, setState] = useState({ count: 0 });

can you change the class component so that it behaves like useState(0)?


If you extend the class component from React.PureComponent it will do a shallow comparison on props and state to determine if it should rerender.

That being said, doing this is usually slower than allowing the component to rerender.


This is a amazing example why react sucks you never know what it does when ok sure if your the inventor of react or study its code you know it but who want's to follow that?

Good Example !


"This is a amazing example why react sucks" this statement is wrong!

It should be "This is an amazing example how javascript handles Objects" Or "This is an amazing example how weird js is"


nope your wrong its react doing this let me explain the function component is a render function thats why it can not get called again and will not get called again the class component has a render function that can and will get called again.


So you can explain anything in Angular, Vue, ... or whatever framework you prefer?


Nice demos there~

It's a confusing concept well-demonstrated.

For Class component version this.setState({ count: value }); you are changing the "reference". For the Function Component, you are changing the primitive, thus the component doesn't re-render.

React re-renders as states change. States change when a "reference" change. Primitive values are stored in stack. This leads understanding of JS.

For more info on how FC & CC differ check out

Classic DEV Post from Dec 8 '19

Question regarding "Junior Full Stack Developers"

An anonymous question regarding junior full stack developers.

sunflowerseed profile image
Front End Dev