score:2
In promise callback, you set the state only once on the first setState(_state);
, on every other try, the component doesn't render because as React rendering works, it makes shallow comparison with the previous state, which is always true because it holds the same object reference (it's javascript):
const state = { a: 1};
setState(state); // prevState = state;
state.a = 2;
prevState === state // always true so not render is triggered
Its a common beginner mistake, React states to treat state as immutable..
score:2
The reason why React
is not rendering the latest state is because you're directly manipulating state
by doing the following:
const _state = { a: 1 };
setState(_state);
// you're using the same object
_state.a = 2;
setState(_state);
// you're using the same object here too
_state.a = 3;
setState(_state);
You should not be mutating state
directly and you should treat state
as it were immutable.
To fix this, you need to make a copy of your state
, update whatever properties you want, and then use that new object to update your state
.
const handleClick = () => {
Promise.resolve().then(() => {
const _state = { a: 1 };
console.log("1");
setState(_state);
console.log("2");
const _state2 = { ..._state, a: 2 };
setState(_state2);
console.log("3");
const _state3 = { ..._state, a: 3 };
setState(_state3);
console.log("3");
});
};
Here's a working example:
Also, React
will batch state
updates so sometimes if you're not seeing "correct behavior" when you call setState
multiple times in a row for the same piece of state it's because React
is trying to prevent unnecessary re-renders by batching those updates. In your case, however, they will not be batched since they are triggered in a Promise
.
See here for more information on how batching works in regards to state updates:
Source: stackoverflow.com
Related Query
- React doesn't render latest state
- React render component even though state doesnt change
- React remove item from array state doesnt re render
- react test state doesnt render while testing
- React JSON mapped data. Trying to pass a setState variable from mapped function will not get the latest state on render
- React - useState - why setTimeout function does not have latest state value?
- Why React needs another render to bail out state updates?
- Destructuring state in React render
- Update React Hooks State During Render Using useMemo
- React hooks state not using latest
- How to stop re render child component when any state changed in react js?
- React on render shows previous state value
- Why React does't compare Previous State and New State before re rendering? Why it always render when setState is called?
- React - How do i force child components to re render when parent state component changes?
- React - will not re render on state change
- get latest state value after setState hook within async await block in react
- ag-grid react cellRendererFramework doesn't re render when state changed
- Too many re-renders. React limits the number of renders to prevent an infinite loop. Updating state of a functional component inside the render method
- React Link tag changes the url but doesnt render the component
- React: using state in a passed callback function to a class constructor doesnt use latest version of state
- Why react doesn't call render when state is changed?
- Dynamically render react component based on parent state
- How to access the latest state value in the functional component in React
- Why does React render component for the second time after setting the state to the same value?
- React import JSON file, store content in State and render it out
- Save latest string values in react state array
- render is not working in react js while using state
- React conditional render based on state
- Why does react component do not re render after changing state
- Getting latest state value with React Hook?
More Query from same tag
- React Native - How to measure size of content in ScrollView?
- TailwindCSS fade in Element on click
- React-native: conditional rendering with loginState
- NextJS error while trying to navigate to dynamic route
- Calling a method (that mutates state) from two different useEffect
- React JS on page load data not getting loaded, however on click its working
- Loading javascript tag into react component
- How to update a map() variable inside a React component, onclick?
- How manage global state using context API in React js
- json not render with reactjs and redux
- How to test Firebase login action (React/Jest)
- How to find when user stops typing in controlled components?
- ReactJS - .JS vs .JSX
- Map the values in object with the given value in react
- Cannot open downloaded zip file from rest endpoint using file-saver
- How to allow only binary digits in input
- Render Component if image src is valid
- react on rails / react intl
- react-hooks/exhaustive-deps warning
- Uncaught TypeError: this.state.people.map is not a function in react js while using the map function
- Why is react-router-dom <Redirect> not working?
- React extremely slow when iterating through JSON
- Using JS packages without npm or yarn
- How to conditionally destructure on object?
- Node.js date incorrect coming from React
- axios post request as query to neo4j graph DB
- My React UI wont update unless i refresh the page
- Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '' is not a valid selector
- How to write the result of the query in the state of React?
- How to save and show the picture saved using Multer package in NodeJS?