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? Please donate!

donate via btc or eth

btc: 18jCzwsZDGQYcs6Kyv92pd4683cnnxm1Dd
eth: 0xC285F21Cb271Cb4B3F70c4C47B2f7B26063AF590
paypal: paypal.me/mrcoles
comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer who lives in NYC, is currently working on this, and blogging here. more »

github · soundcloud · @lethys · rss

It’s time to get big money out of politics. Join the kick-started campaign to put government back in the hands of the people. Pledge mayday.us now