It’s essential to keep your web application scalable and your components reusable. Sometimes you’ll need to set data in one component or page and access it in another. This can be done with Redux but proves problematic in Next JS. So, I’ve been using React’s Context to accomplish this. In this example, I’ll show you how to build a simple loading indicator. You can set the loading state from any component and access it in the loading component. Loading screens keep your visitors happy, but this is just one example of using state across your entire Next JS application.
/lib/context.js
import React, { useContext, useState } from "react";
export const Context = React.createContext();
export const useLoading = () => useContext(Context);
export const Provider = ({ children }) => {
const [loading, setLoading] = useState(true);
return (
<Context.Provider value={{ loading, setLoading }}>
{children}
</Context.Provider>
);
};
/pages/_app.js
import { Provider } from "../lib/context";
import Loading from "../components/Loading";
function MyApp({ Component, pageProps }) {
return (
<>
<Provider>
<Component {...pageProps} />
<Loading />
</Provider>
</>
);
}
export default MyApp;
/pages/index.js
import { useEffect } from "react";
import { useLoading } from "../lib/context";
export default function Home() {
const { setLoading } = useLoading();
useEffect(() => {
if(everythingLoaded) {
setLoading(false);
});
});
return (
<>
Build something stupendous!
</>
);
}
/components/Loading.js
import { useLoading } from "../lib/context";
export default function Loading() {
const { loading } = useLoading();
return (
<>
{loading && 'Loading'}
</>
);
}
Find your audience, refine your product, and create solutions for your customers in the first of your two free consultations.
█