Essential JS for React: Understanding callbacks and arrow syntax

If you are new to JavaScript and React, the syntax can be confusing. You might not know if you are dealing with “React” syntax or “JavaScript” syntax, and it can be hard then to get answers.

One place this crops up alot is with the => syntax used for arrow functions (also called lambda). You might see some code like this in a React component:

const animals = => (<div>{}</div>));
// ... animals is then used in further JSX code

The questions that spring to mind here are:

  • Where is this animal variable declared?
  • Who is calling the function that is passed to map?

To understand this, just think of the arrow function on it’s own:

(animal) => (<div>{}</div>)

It’s an object of it’s own, and the arrow syntax is a shorthand way of saying “this is a function that takes one argument, let’s call it animal, and returns the following JSX.

It is a bit like writing out a function like this*:

function myFunction(animal) {
    return (<div>{}</div>);

*There is a technical difference with the this binding, between a regular function and the arrow function, which we can ignore for our purposes here.

With the written out function, you can more clearly see that animal is declared by the function, and it’s value is determined by the caller. It then returns some JSX, based on the values inside the animal object.

That answers where is animal declared. But who is calling the arrow function?

In the example, the function is passed in to the map function:

const animals = => (<div>{}</div>));
// ... animals is then used in further JSX code

The map function is a built in function of arrays, that takes your function, and runs it against it to every element of the array. Therefore in this instance, it is the built in map function that is calling your function, and it might do it never, once, or many times depending on how big your array is.

Functions can be passed into functions that you create too, or that library authors created. Indeed React allows you to pass a function to setState which when it is ready, will call with the old state value to determine the new state value. In this case it is the React library calling your function.

Understanding functions, arrow functions, and passing functions to other functions is essential if you want an easy time of writing React code. Therefore practice these concepts outside of React first if they seem alien, or you are not at least 90% confident with them.

Posted by Martin Capodici


Leave a Comment

Your email address will not be published. Required fields are marked *