Change Parent Component State from Child using hooks in React

React hooks are introduced in React 16.8. If you are familiar with the class components then there is no difference to change the parent component state from child component.

In both cases, you have to pass the callback function to the parent. Let’s take a very simple example to understand it. We will take two components, Parent and Child. And our Parent component will set the value depends on the Child Component.

Child component holds the Input field and we are going to send the input field value to the Parent component. So let’s create the Parent component first.

function Parent() {
    const [value, setValue] = React.useState("");

    function handleChange(newValue) {
      setValue(newValue);
    }

    // We pass a callback to Child
    return <Child value={value} onChange={handleChange} />;
}

As you see that we set the onChange property to the Child component. Next step is to create the Child component.

function Child(props) {
    function handleChange(event) {
        // Here, we invoke the callback with the new value
        props.onChange(event.target.value);
    }
  
    return <input value={props.value} onChange={handleChange} />
}

On the above codes, we have created function handleChange that will pass the value through props.onChange to our Parent component.

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.