Next JS State Across Pages

Published

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'}
    </>
  );
}

Access Two FREE Consultations!

Every tribe needs a strong leader and people are ready to join yours. So, give them the tools they need with my web app development services today.

Web App Development Services
#gayowned  🌈
Web App Development ServicesWeb App Development ServicesWeb App Development ServicesWeb App Development ServicesWeb App Development Services
Web App Development Services

Web App Development Services