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:
componentDidUpdate(prevProps, prevState) { const prevValue = prevProps.value; this.setState((state, props) => { const nextValue = props.value; if (prevValue === nextValue) return null; const isIncreasing = prevValue < nextValue; if (prevState.isIncreasing === isIncreasing) return null; return { isIncreasing }; }); }
Code without updater:
componentDidUpdate(prevProps, prevState) { const prevValue = prevProps.value; const nextValue = this.props.value; if (prevValue === nextValue) return; const isIncreasing = prevValue < nextValue; if (prevState.isIncreasing === isIncreasing) return; this.setState({ isIncreasing }); }
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:
static getDerivedStateFromProps(props, state) { return { prevValue: props.value, isIncreasing: props.value > state.prevValue, // First time will always be true since state.prevValue is undefined FYI }; }