Let's say I'm having a Parent
Component providing a Context
which is a Store
Object. For simplicity lets say this Store has a value and a function to update this value
class Store {
// value
// function updateValue() {}
}
const Parent = () => {
const [rerender, setRerender] = useState(false);
const ctx = new Store();
return (
<SomeContext.Provider value={ctx}>
<Children1 />
<Children2 />
.... // and alot of component here
</SomeContext.Provider>
);
};
const Children1 = () => {
const ctx = useContext(SomeContext);
return (<div>{ctx.value}</div>)
}
const Children2 = () => {
const ctx = useContext(SomeContext);
const onClickBtn = () => {ctx.updateValue('update')}
return (<button onClick={onClickBtn}>Update Value </button>)
}
So basically Children1
will display the value, and in Children2
component, there is a button to update the value.
So my problem right now is when Children2
updates the Store value, Children1 is not rerendered. to reflect the new value.
One solution on stack overflow is here. The idea is to create a state
in Parent
and use it to pass the context
to childrens. This will help to rerender Children1
because Parent
is rerendered.
However, I dont want Parent
to rerender because in Parent
there is a lot of other components. I only want Children1
to rerender.
So is there any solution on how to solve this ? Should I use RxJS to do reative programming or should I change something in the code? Thanks
updateValue('update')
how does it look like? It seems like issue may be there which may not be updating right object property. – Lordosis