Passing Thought Project: Why does array filter not work properly without callback in removeThought function?

Can someone please explain why in Step 9 when creating the “removeThought” function, the call to “setThought” has to include a callback function versus just directly returning the filtered array.

My original code:

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

The bug I get is after 15 seconds all the current thoughts are deleted, instead of them being deleted individually.

Working code:

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

I just don’t understand how wrapping it in an addition arrow functions changes this behavior.

This is actually a very complex subject involving understanding the underlying mechanisms of how React works. As noted in the link below, setState is an asynchronous function, so we use a callback so that when setState is called, the callback function has the updated state. Suffice to say, though, you don’t need to understand this to work with it.