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
- Why the 'Error: Couldn't find preset "react-hot" relative to directory..." in ReactJS for React Hot Loader?
- How to add "refs" dynamically with react hooks?
- GET http://localhost:8080/main.js net::ERR_CONNECTION_REFUSED on deploying on Netlify console error
- How to limit react-redux connect update re-renders to specific state branches?
- Fonts not found with nested routes in react-router
- how to pass initial state value using immutable js
- reactjs bundle script by browserify not working on the client side (Uncaught ReferenceError: Component is not defined)
- React: Use this.props.children or pass components as named props
- Ant Design Tabs remain unchanged when clicking to browser back button. How to change tabs when state updates
- react redux action not calling reducer
- Cancel of requests through saga
- Create a component that represent two table with OneToMany relation in one table
- React : Fetching data from inputs using createRef
- How to style the individual point using react-google-charts?
- Component typing react typescript
- React Hook complex states, setting nested values
- How to pass multiple parameters to input's onChange handler
- setItem after i setValue of my list not updated with current value
- how to display a random value from an array of objects in an React view
- javascript get specified amount of array when a function is invoked using slice
- check all checkbox in react table
- JS/ReactJS: How to get all input values of a table?
- Load images in React using webpack loader
- Don't allow double space in textarea with React javascript
- How to change routes in gatsby without Link component?
- Adding Title to React Leaflet Map
- Using MUI ThemeProvider causes "undefined" errors
- How to assert a function is called from within another function?
- Warning: Failed propType: Invalid prop `component` supplied to `Route`
- How can I display array elements passed as a prop to functional component?