Why do callbacks work for passing information from the child to the parent in react?

For example if in my parent class I have a function like

getUserInput = (input) => {
   	//does something

And I pass it as props to a child component like
<ChildComponent getUserInput={this.getUserInput} />

And then in the child component I call it as a callback function
<button onClick={() = this.props.getUserInput(input)} </button>

This will allow the parent component to have access to the information and I could set it as state for example

But why does calling a callback of a function sent as props send the information to the parent class? Can anyone clarify this for me?

It doesn’t, necessarily.

But let’s say your function getUserInput had some code that accessed and set variables that are bound to the parent this.state.messageDisplayed using the value of the ChildComponent and shouldn’t be accessible to the child, for example. In this case, as you say,

This will allow the parent component to have access to the information.

The reason this works is closure and the fact that functions are first-class objects in Javascript. getUserInput, defined on the ParentComponent is an Object. As such, it can be “passed by reference” to the ChildComponent, which stores the location(reference) of the instance of getUserInput owned by ParentComponent in a variable that is part of its props object:

//for ChildComponent:
props = {
  getUserInput: reference to ParentComponent.getUserInput
  //alternative way to understand the same thing:
  getUserInput: reference to the instance of getUserInput owned by ParentComponent.

When you call this.props.getUserInput from ChildComponent, you are feeding the parameter input into the function object owned by ParentComponent, which has access to all the variables at the global scope and its lexical scope, the context in which it was declared. It was declared as a member function of ParentComponent, so it has access to everything that is defined on ParentComponent (props, other methods, anything in the constructor, basically).

You’ve butted into one of the topics with which a fair number of junior programmers struggle. I think it’s because it is often explained poorly. The MDN link I provided above does a thorough job, but I think it helps to have a more bird’s-eye view first.

1 Like