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').
Goal: With this sample app, i am trying to use react context to set and get values within same component. I know to get the updated value we can do setState
within the component, but i do not want to do that as i am already setting the value in context , so why not get from same context within the component (Component2
in this case)
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;
setState
using the prevState value, then it updates immidiately. ex: setState((prevState) => return {...prevState, 'updated value'});useEffect(()=>{ //do something }, [context1])