Callback of `setState` is called at not expected time.
See original GitHub issueSee the following code:
class A extends React.Component {
componentWillMount() {
this.setState({
a: 'a'
}, () => {
console.log('setState');
})
}
render() {
return <B></B>
}
}
class B extends React.Component{
render() {
return <div>B</div>;
}
componentDidMount() {
console.log('didMount');
}
}
ReactDOM.render(<A/>, mountNode);
Preact will log:
setState
didMount
React will log:
didMount
setState
I’m not sure if this is a bug?It will be error when access domNode of child component in callback.
Issue Analytics
- State:
- Created 7 years ago
- Comments:17 (10 by maintainers)
Top Results From Across the Web
setState callback not working as expected
This is happening, because you are calling this.setState({ loading: false }); in the end of your function. You are setting loading: true and ......
Read more >React setState usage and gotchas
React 16 onwards, calling setState with null no longer triggers an update. This means we can decide if the state gets updated within...
Read more >When to Use Callback Function of setState in React
When I first read about setState in the React documentation, I said to myself, “Oh this is easy, this does one thing, changes...
Read more >Strict Mode
Warning about deprecated findDOMNode usage; Detecting unexpected side effects; Detecting legacy context API; Ensuring reusable state. Additional functionality ...
Read more >10 React setState Best Practices
When you pass an object to setState, React will merge the existing state with the new one. This can lead to unexpected behavior...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Oh, the state doesn’t seem to be updated in the callback but it is in the render, will try to look into it soon.
@ForsakenHarmony I suppose it depends on your definition of long-term. The non-prefixed versions will be deprecated after version 16, however “UNSAFE_” will still work and be maintained throughout version 17. No guarantees for version 18 and beyond, however that is a distant future. Should we dismiss the use-case because one day, years down the line, the API may be gone entirely?