Basic context sharing
This would be in a file like lib/context.js
or context/stand.js
import React from "react";
const StandContext = React.createContext();
function StandProvider({ children }) {
// could use a reducer here for more substantial state
const [state, setState] = React.useState({});
const updateState = update => setState({ ...state, ...update });
return (
<StandContext.Provider value={[state, setState]}>
{children}
</StandContext.Provider>
);
}
export { StandContext, StandProvider };
If it is on the app level, we'll need to use a custom _app.js
.
import { StandProvider } from "../context/stand";
function MyApp({ Component, pageProps }) {
return (
<StandProvider>
<Component {...pageProps} />
</StandProvider>
);
}
export default MyApp;
Then, in any file we need to use it, we use the context.
Note, this needs to be within the Provider.
import React from "react";
import Link from "next/link";
import { StandContext } from "../context/stand";
export default function AboutPage() {
const [state, setState] = React.useContext(StandContext);
return (
<>
<div>About us</div>
<Link href="/">Home</Link>
<input
value={state.profile}
onChange={e => setState({ profile: e.target.value })}
/>
<pre>{JSON.stringify(state)}</pre>
</>
);
}
Here's a CodeSandbox with this setup. https://codesandbox.io/s/heuristic-zhukovsky-krtz0?file=/pages/about.js