I am trying to lift state up. I have four different components Parent, Child1, Child2 and Child3.
The parent component has a default value of ‘Hi’. The default value gets updated to ‘Hi2’ in Child3 component. I want Child1 component to get this updated state of ‘Hi2’ from Child3 component. How can I do this?
import React, { useState } from 'react';
function Parent() {
const [value, setValue] = useState('Hi');
return (
<div>
<Child1 value={value} />
<Child2 setValue={setValue} />
</div>
);
}
function Child1({value}) => {
const fetchValue = () => {
console.log('value is: ', value);
}
return (
<div>
<Text value={value}/>
</div>
);
}
function Child2({setValue}) => {
return (
<div>
<Child3 setValue={setValue}/>
</div>
);
}
function Child3({setValue}) => {
const fetchResults = () => {
setValue('Hi2');
}
return (
<div>
<Button click={fetchResults }/>
</div>
);
}
2
Answers
A child component should not change the state of something in the parent component.
So when you do this:
The responsibility of changing the value is being passed from parent to Child2, which breaks the purpose of "lifting state up".
Your parent should hold / change the state and then pass this state’s result to the children. The children should not be aware of each other but only the parent, so that means your child1 should not know about the existence of child3.
So putting that into mind, to refactor it would look like:
There are few syntax errors in the code. Here is the corrected code.