I have 3 component say ParentComponent
, MiddleComponent
and ChildComponent
. ParentComponent has a boolean var
say isPresent
. It is being passed as props to MiddleComponent
which passes the var isPresent
to the ChildComponent
.
In this ChildComponent
, I am doing calculation and changing value of isPresent
. Had it been only one component, I would have used useEffect()
but it is just the value that is being changed and I need to update the same in ChildComponent
and ParentComponent
and not in MiddleComponent
. I do not want to use Virtual DOM and using temporary state might not be the solution as there is hierarchy of Components and later it might cause issues once it gets complex.
Is there a way to use the same variable isPresent
and update in ParentComponent
and ChildComponent
at the same time? It works perfectly fine if I refresh the page as updated value is being fetched from DB directly.
2
Answers
You could achieve this with a state management library like Redux to store application wide states. Your components can access and modify this state using actions and reducers. When a state is updated, all the connected components will be notified and receive the updated values.
If you don’t want to use the state management library you can use context hook to achieve this.