setState takes a function – learnreact

setState takes a function  #setstate #react #javascript #reactjs

  • setState takes a functionA gentle introduction to setState, pt 3.
  • Component state can be updated with object or a function.This is a confusing feature.
  • So, let’s explore both forms of setState and see which events they are best suited for.setState with an objectThe object form of setState is great when setting state that isn’t concerned with previous state.this.setState({ name: “Michael” });Consider an input event handler that updates state as you type.
  • We know the new value and don’t care what the previous value was.
  • So, we replace it wholesale.handleChange(event) { return this.setState({ name: event.target.value }));The object form is great for this.

This is a confusing feature. So, let’s explore both forms of setState and see which events they are best suited for. Consider an input event handler that updates state as you type. We know the new…

@ReactDOM: setState takes a function #setstate #react #javascript #reactjs

A gentle introduction to setState, pt 3.

Component state can be updated with object or a function.

and see which events they are best suited for.

is great when setting state that isn’t concerned with previous state.

this.setState({ name: “Michael” });

Consider an input event handler that updates state as you type. We know the new value and don’t care what the previous value was. So, we replace it wholesale.

The object form is great for this.

The function form is great when transitioning or modifying existing state.

Consider a component that counts clicks. It needs to know the component’s previous state to inform the next state.

in the object form”, you’re not alone. I see this frequently:

There’s a problem here.

an unreliable source for reading previous state.

Think of the function form as writing update instructions. It’s like telling React “Look, I’m not sure what the current state is but update it, using these instructions.”

(We’ll explore queuing in a future post)

You could. But you’ll find cases like this:

setState takes a function – learnreact