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

https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-front-end-development/tracks/fscj-22-react-part-ii/modules/wdcp-22-function-components-and-hooks-a2dba9bf-fc64-4118-8656-dfdc35f9e5cc/projects/react-hooks-passing-thoughts

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 => thought.id !== 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 => thought.id !== 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.

2 Likes