Home > other >  Understanding react function notation
Understanding react function notation

Time:01-05

Learning react here. Can someone walk me through how to interpret the function below:

const onElementsRemove = (elementsToRemove) => setElements((els) => removeElements(elementsToRemove, els));

As far as I understand it, this is the same as calling:

onElementsRemove(setElements(elementsToRemove(els))? 

Is that correct? Is there a benefit to the first notation? Perhaps I am biased coming from the python side of the world but the second one feels more compact? Can someone help me undrstand the reasoning? Thanks!

CodePudding user response:

No, those are not the same. Let's start with the inner part, which needs to be the way it is:

setElements((els) => removeElements(elementsToRemove, els))

When setting state in react, there are two options. You can either directly pass in what you want the new state to be, or you can pass in a function. If you pass in a function, then react will look up what the latest value of the state is, and call your function. Then you return what the new state will be.

So the purpose of doing it this way is to find out what the latest value in the state is. There isn't another way to do this.

Next, the outer part, which has more flexibility:

const onElementsRemove = (elementsToRemove) => /* the stuff we looked at earlier */

This is defining a function called onElementsRemove. From the name, i assume that this is going to be called at some arbitrary point of time in the future. So it's just defining the functionality, and later on you can call it, once you know which elements you want to remove. It will then turn around and set the state. For example, you would do:

onElementsRemove([1, 2, 3]); // i don't actually know what will be in the array

Maybe having this outer function is useful, maybe not. If you're having to do this fairly often it could make sense. In other cases, maybe you could directly call setElements, as in:

setElements((els) => removeElements([1, 2, 3], els));
  •  Tags:  
  • Related