I am having a sample react app with 2 components Component1
& Component2
as below.
i am using useContext
hook to update the context value in Component2
and reading the updated context value in Component1
.
This is working as expected and i am able to read the updated value from context in Component1
Issue:
If i am trying to read the context value after updating it in Component2
itself, then its printing the prev values (‘initial text’) and NOT the latest updated value (‘updated text’).
AppContext.tsx
const AppContext = createContext('create context text');
export default AppContext;
Root.tsx
export const Root = (props) => {
const [context1, setContext1] = useState('initial text');
return (
<AppContext.Provider value={{context1, setContext1}}>
{props.children}
</AppContext.Provider>
)
}
App.tsx
const App = () => {
return (
<Root>
<Component1></Component1>
<Component2></Component2>
</Root>
)
}
export default App
Component1.tsx
const Component1 = () => {
const {context1, setContext1} = useContext(AppContext);
console.log('context ', context1); // **This prints 'updated text' as expected**
useEffect(() => {
console.log('Comp1 useEffect');
},[]);
const buttonHandler2 = () => {
console.log('appname context updated ' + context1);
}
return (
<>
<div>comp1 Name: {context1} </div>
<button onClick={buttonHandler2}>Check name</button>
</>
);
}
export default Component1;
Component2.tsx
const Component2 = () => {
const {context1, setContext1} = useContext(AppContext);
useEffect(() => {
console.log('Comp2 useEffect');
},[]);
const buttonHandler = () => {
setContext1((prev) => {
return 'updated text';
});
console.log('context ', context1); //This prints 'initial text', but since we are doing
//setContext above, it should print 'updated text'
}
return (
<>
<button onClick={buttonHandler}>Update name</button>
</>
);
}
export default Component2;