07 December 2018

How to use functional setState in React

this.setState((state, props) => {
  return {counter: state.counter + props.step};
});

params: the current state and props as positional arguments

This matters, because `setState` is asynchronous, so there’s a risk of overwriting things like toggle-able elements or nested objects if run in a loop or another repeated way inside a function.

return: an object to apply to your component’s state

Whatever you return will be applied to the state like a normal `this.setState({…})` call, i.e., `Object.assign(this.state, newState)`, plus all the React update stuff that happens.

Maybe writing this down will help me remember the syntax of how to pass a function into setState. See the React docs for more.




Did you find this helpful or fun? paypal.me/mrcoles
comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer living in NYC who is building Superset 💪 and also created GoFullPage 📸
more »

github · soundcloud · rss