I am using multiple state variables in a React function component and wish to update both the states (namely columns and rows for a table). I am using the useState
hook for maintaining the states. Will using setColumns
and setRows
(the setters of the 2 states) on consecutive lines work for me ?
Because once the first state would be updated, the whole component will get re-rendered, so how will the next state be updated then? I am very skeptical about this.
If this won't work, what is the workaround for this ? Pls help.
UPD: Clarifying the question a bit more. I have a table for which I am maintaining 2 states (one for columns and one for the data (rows)). Now, in some function, I wish to update the state of both columns and rows. Since we don't have the luxury of doing it at once like in setState
in a class component, I plan to do the updates on consecutive lines. But since each update would lead to a re-render, I am not sure if the 2nd state update would work.
CodePudding user response:
I don't know if I got your question, but using 2 setters in consecutive lines will work fine. Each setter will set the new value of the variable for the next rendering.
In case your second setter depends on the first, you will need to use an useEffect()
hooks to handle your setter.
See this example https://dev.to/shareef/react-usestate-hook-is-asynchronous-1hia
CodePudding user response:
Before React 18, multiple state updates were batched. If you set multiple set states, it will only re-render one time. Except for promises, settimeout like async operations. If you set multiple states in a setTimeout, it will re-render multiple times.
After React 18, every multiple state update will be batched. Even it is in promises, settimeout, etc. like async operations.
For further information search: "react batch update"