Get updated value from Child to Parent – React

In this tutorial, we will learn how you can get updated value from child component to parent component in React.

Let’s say you have a parent child component in your React app. You are sending data from parent to child and your child component is updating that variable’s value. Now when you get the value in parent component, you still get the original value, not the updated one.

First, you need to create a reference and pass it to the child component.

function Parent() {

    // Create a reference
    const childRef = React.useRef();

    // Create array of users
    const [users, setUsers] = React.useState([
        { id: 1, name: "Adnan" },
        { id: 2, name: "Afzal" }
    ]);

    // Function to get updated users
    function getUsers() {

        // Get users with reference
        let tempUsers = [];

        if (childRef.current) {
            tempUsers = childRef.current.getUsers();
        }

        console.log({
            "users": users,
            "tempUsers": tempUsers
        });
    }

    // Set child component and pass users array to it
    return (
        <>
            <Child users={ users }
                ref={ childRef } />

            {/* Button to get users */}

            <button type="button" onClick={ function () {
                getUsers();
            } }>Get users</button>
        </>
    );
}
  • childRef: First, we are creating a reference.
  • users: Then we are creating a state variable.
  • getUsers(): A function is created that will get the state value using reference.

We are passing the users array and reference to the child component.

A button is also created which when clicked, will call the function to get the state variable.

Then in your child component, you need to create it using forwardRef.

// Create child component that gets properties
// Export child using forward reference
const Child = React.forwardRef(function (props, ref) {

    // Get users from parent component
    const [users, setUsers] = React.useState(props.users || []);

    // Use imperative handler to return updated value
    React.useImperativeHandle(ref, function () {
        return {
            getUsers() {
                return users;
            }
        };
    });

    // Function to set user name to "Khalid" where user ID is 1
    function updateUser(id, name) {
        const tempUsers = JSON.parse(JSON.stringify(users));
        for (let a = 0; a < tempUsers.length; a++) {
            if (tempUsers[a].id == id) {
                tempUsers[a].name = name;
                break;
            }
        }
        setUsers(tempUsers);
    }

    // Create button to update user
    return (
        <>
            <button type="button" onClick={ function () {
                updateUser(1, "Khalid");
            } }>Update user</button>
        </>
    );
});

forwardRef: It is used to pass ref from parent component to child component.

Then creating a state variable and initialize it with props value received from parent component.

We are using imperative handler to return the updated value.

A button is created in child component that updates the value using it’s ID.

JSON.parse(JSON.stringify(users)): We are first converting the users array to JSON, then converting back to Javascript array. This ensures a deep copy.

That’s how you can get updated value from child component to parent component in React.