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?
JavaScript
x
38
38
1
import React, { useState } from "react";
2
3
const Parent = () => {
4
const [someState, setSomeState] = useState("Initial Some State");
5
6
const onChangeSomeState = (newSomeState) => {
7
setSomeState(newSomeState);
8
};
9
10
return (
11
<div>
12
Parent:
13
<Child
14
someState={someState}
15
onChangeSomeState={onChangeSomeState}
16
></Child>
17
</div>
18
);
19
};
20
21
const Child = ({ someState, onChangeSomeState }) => {
22
const handleChangeStateClick = () => {
23
onChangeSomeState("New Some State from Child");
24
};
25
return (
26
<div>
27
Child:{someState}
28
<input
29
type="button"
30
onClick={handleChangeStateClick}
31
value="Change state from Child"
32
></input>
33
</div>
34
);
35
};
36
37
export default Parent;
38