Skip to content
Advertisement

React: Changed state in Child component. How to see the change in parent component?

For a website I am working on I have made a component with checkboxes that triggers a state change in a parent component. I have checked in the console through the child component that the state is changed, but I want the parent component to “notice” the change too. I have tried useEffect and componentDidUpdate but they both do not get triggered by the state change.

To clarify, the structure looks like this:

Parent: Has the initial state Child: Gets access to state through parent, and changes state

On a page refresh the parent notices the state change, but I want this without having to refresh the page.

I hope this makes sense, thank you in advance 🙂

Advertisement

Answer

Is this what you are looking for?

import React, { useState } from "react";

const Parent = () => {
  const [someState, setSomeState] = useState("Initial Some State");

  const onChangeSomeState = (newSomeState) => {
    setSomeState(newSomeState);
  };

  return (
    <div>
      Parent:
      <Child
        someState={someState}
        onChangeSomeState={onChangeSomeState}
      ></Child>
    </div>
  );
};

const Child = ({ someState, onChangeSomeState }) => {
  const handleChangeStateClick = () => {
    onChangeSomeState("New Some State from Child");
  };
  return (
    <div>
      Child:{someState}
      <input
        type="button"
        onClick={handleChangeStateClick}
        value="Change state from Child"
      ></input>
    </div>
  );
};

export default Parent;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement