score:689
from react's documentation:
setstate()
does not immediately mutatethis.state
but creates a pending state transition. accessingthis.state
after calling this method can potentially return the existing value. there is no guarantee of synchronous operation of calls tosetstate
and calls may be batched for performance gains.
if you want a function to be executed after the state change occurs, pass it in as a callback.
this.setstate({value: event.target.value}, function () {
console.log(this.state.value);
});
score:0
simply putting - this.setstate({data: value}) is asynchronous in nature that means it moves out of the call stack and only comes back to the call stack unless it is resolved.
please read about event loop to have a clear picture about asynchronous nature in js and why it takes time to update -
https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4
hence -
this.setstate({data:value});
console.log(this.state.data); // will give undefined or unupdated value
as it takes time to update. to achieve the above process -
this.setstate({data:value},function () {
console.log(this.state.data);
});
score:0
react bathces different set state calls so that it can determine what is the most optimal strategy for rerendering the website is going to be.
imagine you have an application where you have a lot of different components. perhaps, with one button click you are updating the state in multiple components, not just on the current one. in this case, react does not want to just completely isolate and do all those different updates independently.
react wants to figure out if it can stack all these updates together, maybe there is a more optimal way of updating these components so that it is more performant. this is what react is doing behind the scenes. as a result, set state call is asynchronous call.
score:1
accessing this.state
after calling the setstate
method is not guaranteed to return the updated status due to the asynchronous nature of setstate
.
to guarantee an update after calling setstate
, there are two solutions you may pursue.
solution 1: as mentioned in one of the above answers, put your code in the componentdidupdate
method
solution 2: as mentioned in another of the above answers, pass your stuff as a callback
this.setstate({value: myvalue}, function () {
this.functionthatisexecutedwhenstateisupdated();
});
it's important to note that these two solutions are not clearly interchangeable. the one cannot easily solve all the use-cases of the other. as a general rule, if you can, best practice says that solution 1 is preferred. but, there are use-cases where only solution 2 "more effectively" works such as the "update-my-view-and-post-my-data" use case. this use case goes like this:
after adding an item, say, "add schedule", i want to both add that item to a front-end list and immediately post the just-updated-list to the backend, as demonstrated in the concept below:
if you dont do either solution, i.e. if you only say this in your code:
addtoitemarray = () => {
this.setstate{{ scheduleditemsarray: newobjectlistwithmax}}
this.postdata();
}
<button classname="btn btn-secondary btn-block" onclick={this.addtoitemarray}>add shedule</button>
... you will post the list excluding the "delivery to max" item, because the state wont be updated when you this.postdata()
(again, because its asynchronous).
if you utilise solution 1, you would make a post after typing in every character in the schedule name textbox!
there are other ways aswell to cater for this use-case but solution 2 best conveys the intent when reading the code.
given the ubiquitous nature of this use case in virtually every web app, the callback technique explained by michael's answer is an indispensable piece of code in every developers toolkit.
score:2
async-await
syntax works perfectly for something like the following...
changestatefunction = () => {
// some worker..
this.setstate((prevstate) => ({
year: funchandleyear(),
month: funchandlemonth()
}));
gonextmonth = async () => {
await this.changestatefunction();
const history = createbrowserhistory();
history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}
goprevmonth = async () => {
await this.changestatefunction();
const history = createbrowserhistory();
history.push(`/calendar?year=${this.state.year}&month=${this.state.month}`);
}
score:13
watch out the react lifecycle methods!
- http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
- https://reactjs.org/docs/react-component.html
i worked for several hours to find out that getderivedstatefromprops
will be called after every setstate()
.
😂
score:24
you could try using es7 async/await. for instance using your example:
handlechange: async function(event) {
console.log(this.state.value);
await this.setstate({value: event.target.value});
console.log(this.state.value);
}
score:54
as mentioned in the react documentation, there is no guarantee of setstate
being fired synchronously, so your console.log
may return the state prior to it updating.
michael parker mentions passing a callback within the setstate
. another way to handle the logic after state change is via the componentdidupdate
lifecycle method, which is the method recommended in react docs.
generally we recommend using componentdidupdate() for such logic instead.
this is particularly useful when there may be successive setstate
s fired, and you would like to fire the same function after every state change. rather than adding a callback to each setstate
, you could place the function inside of the componentdidupdate
, with specific logic inside if necessary.
// example
componentdidupdate(prevprops, prevstate) {
if (this.state.value > prevstate.value) {
this.foo();
}
}
Source: stackoverflow.com
Related Query
- Why does calling react setState method not mutate the state immediately?
- Why calling setState method doesn't mutate the state immediately?
- Why does setState Hook from React is rendering twice even not changing the state?
- React Hooks: updating state using useState does not update the state immediately
- Why does using an arrow function give the updated version of the state in React in comparison to calling the function normally?
- useState React Hook set method does not update state immediately in onChange()
- The state changed but the render method from react does not trigger
- React why the state is not updating when calling a function to initialize it?
- React : why state change when try to change it in immutable way , before calling the setState
- Why does the state object in react not update properly? Expanded and collapsed version of object differ
- Why does my React app menu open when I am only changing the state and am not using any CSS?
- Why does my Auth.currentAuthenticatedUser() method return updated state after I reload and not when the useEffect's dependency runs (or login/logout)?
- Why does my state not change or work the first time I click submit in React
- React setState does not change the state
- Why formData does not take the data there is in the state and that has been refreshed, there is a delay character ? React
- Why does React rerender when the state is set to the same value the first time via an onClick event on DOM, but not react-native?
- React Hook error in array handing in useEffect() and setState does not set the state
- Why does not the background color get applied from props using state for a styled component div using react and typescript?
- React - useState - why setTimeout function does not have latest state value?
- Why does React warn me against binding a component method to the object?
- Why does my Animated view not stay in the correct place in React Native?
- Why getDerivedStateFromProps does not allow to re-render with the state update? Not a problem for componentWillReceiveProps - ReactJS
- React leaflet center attribute does not change when the center state changes
- Why does React have to use setState for state update?
- React does not refresh after an update on the state (an array of objects)
- Why does calling useState's setter with the same value subsequently trigger a component update even if the old state equals the new state?
- Why does calling the set function of a useState hook apply immediately in async functions?
- Why does React throw an error when setState method used in a class constructor?
- In React why does calling a function from another function in our code not work and display?
- React setState does not set state during a while loop
More Query from same tag
- How to get data nested with nested fields in redux-form?
- React use setState to update book shelf
- React Hook Form 7 custom ...register values
- How to delete an element in list in react?
- React/Redux Component will not render
- Delete item from list not rendering react js
- How can I make onClick() not trigger when I click another onClick() inside of it?
- Typescript wrapping types
- filter in react with multiple conditions
- React JS state that references other state property
- How to use async functions in react redux
- Passing props from one class component to other in react js
- TypeError: rtdb.initStandalone is not a function
- React: setState causes app crash
- socket.io with Node.js and React.js UI does not update when I open multiple tabs or another tab in a different browser
- Single responsibility in React component
- Cursor at very start of first line in Draft.js editor
- ReactJS: how to add a functionality to any React Component by default in my app
- React component flickers on first change in local state
- Trying to use redux-thunk, but it displays error even though everything seems fine to me
- setState in React not giving desired output
- React Router v4: Prevent navigating back
- Type of Link component passed as 'component' prop
- Can't work setTimeout in componentDidMount
- I want to handle linkWithPopup and Firebase `auth/credential-already-in-use` error in this case
- How to send POST request to Django API from ReactJS web app?
- Count the values count which got from the url parameters React
- Hide Div onClick when clicking outside the child div | ReactJS
- Can't find variable: _d when running react native app for the first time
- Highlight a word in a row of a table in Reactjs