I've this parent component(Parent
) which holds an inner component(InnerComp
) (for organizing code). The inner component has another nested component(Comp
) which I'm importing from another file. to update Parent
's state from Comp
, I'm passing the setParentCount
function via prop in Comp
function Parent() {
const [parentCount, setParentCount] = useState(0);
const InnerComp = () => (
<>
<h2>necessary inner comp</h2>
<hr />
<Comp setParentCount={setParentCount} />
</>
);
return (
<>
<h1>Parent</h1>
<hr />
<InnerComp />
<p>parent comp count = {parentCount}</p>
</>
);
}
Comp
has its own state as well. the "Click" button in Comp
calls the handleClick
function on click. the handleClick
function is trying to update both the Comp
and Parent
's state. but it seems that compCount
is not getting updated.
function Comp({ setParentCount }) {
const [compCount, setCompCount] = useState(0);
useEffect(() => {
console.log(compCount);
}, [compCount]);
function handleClick() {
setCompCount((prev) => prev + 1);
setParentCount((prev) => prev + 1);
}
return (
<>
<h3>child comp</h3>
<button onClick={handleClick}>Click</button>
<p>child comp count = {compCount}</p>
</>
);
}
I've added the useEffect
as well for compCount
in Comp
. it's logging every time I click the button. but the same initial value. means the setCompCount
function is setting the old value every time. I wonder why it is happening.
When I add the InnerComp
's JSX directly inside Parent
instead of making a new inner component, it works fine. But I kinda need the InnerComp
to keep my code organized.
I know I can make it work with useContext
, but I think having context here will make this tiny component really heavy.
Here's a codesandbox