Skip to content
Advertisement

Should I use setState conditional updates in componentDidUpdate in React 16?

I’m using React 16 and need to call a conditional setState inside componentDidUpdate. setState is executed asynchronously. So, usually, if I need to use state to compute my next state I should use updater function as an argument to setState. React 16 added a possibility to cancel a setState update by returning null from setState. So, should I use updater function to make a conditional setState?

Code with updater:

JavaScript

Code without updater:

JavaScript

Advertisement

Answer

I think there is no difference other than stylistically. Personally I prefer the second approach. Either way you will cause another render cycle so alternatively you could use getDerivedStateFromProps which will run before the component renders and doesn’t require conditionals to prevent infinite loops:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement