Skip to content
Advertisement

React Setstate callback called but render delayed

I just started to learn to react 2 days ago and I’m having a hard time with react’s setstate method, all I know is use revstate parameter if want to change state based on previous state, and callback parameter to be executed right after the state change (please correct me if this wrong), so I just change the array content (which I render it using javascript’s array.map) and I wish it renders right after the state is changed, it is changing but delayed, it only render after I do another click but the render method is called for any senpai out there thanks for the help.

Handle click for changing to render content based on index passed on my button “onClick”

JavaScript
JavaScript

Advertisement

Answer

Refactor your code and Approach the simpler way

Actually, you shouldn’t use the second param callback.

Whenever the state is changed, the life cycle of React Js will re-render it properly (See the image below to clarify in detail ^^!)

There are some things to note:

  • Move the content of each item in torender accordingly –> This is clearer about the initial data as well as it should not be mutated.

  • Default clickeditem is one of the items in torender, for example, the first item.

  • After that, you just control the content to be rendered in this way

    JavaScript

JavaScript
JavaScript

enter image description here

Advertisement