React Components Using callback Functions to Communicate up the Component Tree

Abel Gechure
2 min readAug 13, 2021

Learning React has been an absolute joy in the most part especially once you figure out how things are working. One of the things that was a challenge for me was understanding how to maintain a single source of truth in my component tree. That is why I decided to write about this.

Usually components can have their own state but sometimes its more recommended to lift the state up to a common parent component and get the state down passed down as props using callback functions.

I will be building a simple app that demonstrate this concept. The scenario is having a parent component that returns a container div. Inside that div want to nest a child component that has an input field and this input field will be responsible for setting the background color of its parent component.

lets create the parent component.

import React,{useState} from 'react'
import ColorBox from './ColorBox'
const App = () => {
const [color, setColor] = useState('')
const handleColorChange = (event) => {
setColor(event.target.value)
}

return (
<div className="App" style={{backgroundColor: color}} >

<ColorBox onChange={handleColorChange} color={color}/>

</div>
);
}
export default App

As you can see we have a parent component that maintains state value or color. We are importing a component coloBox and we are passing down some props onChange. onChange is a prop that is set to a function that updates the state by using the setState state updater function and we are also passing down the color prop that holds the current state value.

Now lets define the ColorBox component.

import React from 'react'const  ColorBox = ({color, onChange}) => {
return (
<div>
<form>
<p>
<label>Enter Color </label>
<input type='text' onChange={onChange} value={color} />
</p>
</form>
</div>
)
}
export default ColorBox;

As you can see we defined a ColorBox component here that returns a form . This form has only one input element. The ColorBox component receives props and we use the onChange attribute of the input element to point to a callback function onChange which is set to handleColorChange defined in our parent component. It is fired everytime someone types in the input field and the state is updated. This is essentially what lifting state means. Then you can use the new value of the state to change the background color of the App component. One more thing is we passed the state value to our input element as props making our form a controlled component

This is a simple example meant to show you that you can pass state and callback functions down as props and the children components can be able to communicate up to their parent components using those callback functions.

--

--