Function Components Syntax Question

I’m finishing the project Passing Thouhts from the course Learn React and I just got stuck in what appears to be just a syntax bug. Project Passing Thoughts - Learn React

Inside the function component <App/> on the main App.js file the following function will work just fine:

const removeThought = (thoughtIdToRemove) => {
    setThoughts((thoughts) => 
      thoughts.filter((thought) => thought.id !== thoughtIdToRemove)
    );
  };

However, If I write the function as I did the first time (below), using the {} around the main body of the setToughts(), the web crashes when trying to remove the thought.

const removeThought = (thoughtIdToRemove) => {
    setThoughts((thoughts) => {
      thoughts.filter((thought) => thought.id !== thoughtIdToRemove)
    });
  };

The only difference I find are the curly braces, and I can’t understand why they result in a bug.

With the {} brackets, the setThoughts function does not return anything. Without them, the function returns (implicitly) and then sets the thoughts state variable to the result of the .filter call appropriately.

2 Likes

Hey Javaace

Just tried refactoring the code with the curly braces and Return keyword. Works perfectly as well!

I was not aware that the setState() functions had to Return the newly defined state. Probably all the examples throughout the course are set with arrow functions returning implicitly (as you explained), the thus I have missed that little detail.

Thanks for your explanation! It was super enlightening!

1 Like

You are exactly correct. setState does indeed require a return, and this is often done with an implicit return where possible.

1 Like