Calling setState in componentDidUpdate
See original GitHub issueIt might be worth revisiting react/no-did-update-set-state.
Now that componentWillReceiveProps()
is being deprecated, componentDidUpdate()
is the only “safe” way to detect changes in props and set state accordingly.
The React docs say calling setState()
in componentDidUpdate()
is permitted, albeit with caveats.
You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:117
- Comments:11 (2 by maintainers)
Top Results From Across the Web
setState() inside of componentDidUpdate()
You can use setState inside componentDidUpdate . The problem is that somehow you are creating an infinite loop because there's no break condition....
Read more >React.Component
You may call setState() immediately in componentDidMount() . It will trigger an extra rendering, but it will happen before the browser updates the...
Read more >Using componentDidUpdate in React
The componentDidUpdate is a part of a React component life cycle. We use it to react to external changes in component's props or...
Read more >Post-Render with componentDidUpdate() · react-indepth
This may require us to update our internal state or props for our children. If this is the case we can call this.setState()...
Read more >Hi! You can call setState in the lifecycle methods ...
Hi! You can call setState in the lifecycle methods componentWillUpdate and componentDidUpdate. To prevent the infinite loop you need to add ...
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
Polluting
state
with previous props/state really sucks.The new lifecycle method
getDerivedStateFromProps
is not a perfect replacement forcomponentWillReceiveProps
as it does not provide access toprevProps
.