Tutor How
Tutor How

Reputation: 48

Nextjs - Access global context values

I would like to see how I can create global contexts in NextJS and have global variables inside the app.

Currently I have AppContext.js as

import { createContext } from 'react'

const AppContext = createContext();

export default AppContext

_app.js


const [socketio, setSocketio] = useState(null);
const appContext = {
  socketio
};

return(
  <AppContext.Provider value={ appContext }>
    <Component {...pageProps} />
  </AppContext.Provider>
)

How can I access the appContext values from another component? Thank you!

Upvotes: 1

Views: 1782

Answers (1)

Ajith Gopi
Ajith Gopi

Reputation: 1836

You can use useContext(AppContext) to access the data from any component... Like:

const appContext = useContext(AppContext);

And access each value like

appContext.socketio

Upvotes: 1

Related Questions