I'm a little confused on some of the code in this lesson

In this lesson on state hooks, we have this code:

  handleChange({ target }){
    const { name, value } = target;
    this.setState((prevState) => ({
      newTask: {
        [name]: value,
        id: Date.now()

I’m a little confused. What does ...prevState do, and what does putting an anonymous function in this.setState() do? I didn’t know we could do that, and I don’t understand why they’re doing it.

This is from the AppClass.js class component version, not the function component version.

The first ...prevState actually doesn’t do anything useful here since setState() does shallow merging. The ...prevState.newTask one is important though in order to maintain the other properties of newTask. If you’re interested in a much more in-depth discussion of this specific block of code, along with examples, you can check this thread

As for why there’s an anonymous arrow function there, using it ensures that the latest state is being used since setState() doesn’t guarantee an immediate update of the component or this.state. Since they are copying existing keys/values from newTask, we can be sure it’s the most up to date state using the callback. You can read more about that here. There are more options for the callback too - it can also have a props parameter.

1 Like

Thanks that was helpful, but what does the ... specifically do or mean?

That’s using spread syntax. It can be used in a variety of ways. Here’s how it can be used with objects, like the state. Spread Syntax in Object Literals

1 Like

Thanks, that’s what I after. The other stuff was educational too, though.