I have a parent Component and two child Component as below:
ParentComponent:
import React, { useState } from "react";
import { Child1Comp } from "./Child1Comp";
import { Child2Comp } from "./Child2Comp";
export function ParentComp() {
const [step, setStep] = useState(1);
const [parentState, setParentState] = useState({});
const handleNextBtn = () => setStep((step) => step + 1);
const handlePrevBtn = () => setStep((step) => step - 1);
return (
<div>
<div>{`the parent state is: ${JSON.stringify(parentState)}`}</div>
{step === 1 && (
<Child1Comp
step={step}
parentState={parentState}
setParentState={setParentState}
/>
)}
{step === 2 && (
<Child2Comp
step={step}
parentState={parentState}
setParentState={setParentState}
/>
)}
<br />
<button
id="nextBtn"
name="nextBtn"
onClick={handleNextBtn}
disabled={step === 2}
>
Next
</button>
<button
id="nextBtn"
name="nextBtn"
onClick={handlePrevBtn}
disabled={step === 1}
>
Prev
</button>
<br />
<br />
{`current step is : ${step}`}
</div>
);
}
Child1Component:
import React, { useEffect, useState } from "react";
export function Child1Comp({ step, parentState, setParentState }) {
const [inputValue, setInputValue] = useState();
const handleChange = (e) => setInputValue(e.target.value);
useEffect(() => setInputValue(parentState.child1), []);
useEffect(
() =>
setParentState((parentState) => ({
...parentState,
child1: inputValue
})),
[step]
);
return (
<div>
<br />
name:
<input
id="child1"
name="child1"
value={inputValue}
onChange={handleChange}
/>
</div>
);
}
Child2Component:
import React, { useEffect, useState } from "react";
export function Child2Comp({ step, parentState, setParentState }) {
const [inputValue, setInputValue] = useState();
const handleChange = (e) => setInputValue(e.target.value);
useEffect(() => setInputValue(parentState.child2), []);
useEffect(
() =>
setParentState((parentState) => ({
...parentState,
child2: inputValue
})),
[step]
);
return (
<div>
<br />
family:
<input
id="child2"
name="child2"
value={inputValue}
onChange={handleChange}
/>
</div>
);
}
- In the parent Component, I have a step state for determining which child should be shown.
- Each child has itself state.
now I want when the user changes the step value by clicking on the Next button, the child state value save in the parent state, so I use this code in each child:
child1:
useEffect(
() =>
setParentState((parentState) => ({
...parentState,
child1: inputValue
})),
[step]
);
child2:
useEffect(
() =>
setParentState((parentState) => ({
...parentState,
child2: inputValue
})),
[step]
);
but when the step state changes in the parent Component, none of the top useEffect runs. and child state not save in parent state.:(
Do you have any idea to solve this problem?