The source code for this blog is available on GitHub.
Note
Top

Using the useContext Hook in Next.js for Managing Global State

Cover Image for Using the useContext Hook in Next.js for Managing Global State
Chen Han
Chen Han

Cart Context

/* eslint-disable react/jsx-props-no-spreading */
import Router from "next/router";
import "../styles/globals.css";
import { SessionProvider } from "next-auth/react";
import { RecoilRoot } from "recoil";
import Head from "next/head";
import Markdown from "@/components/Markdown";
import Snackbar from "@/components/Snackbar";
import useCart from "@/hooks/cart.hook";
import { getCookie } from "@/lib/cookies";
import { createContext, useReducer, useEffect } from "react";
import * as schema from "@/components/seo/schema";

const initCartNumContext = {
  cartNum: 0,
  cartId: undefined,
};
export const CartNumContext = createContext(initCartNumContext);

function MyApp({ Component, session, pageProps }) {
  const [cartNum, setCartNum] = useCart();

  let cartId;
  if (!!globalThis.window) {
    setCartNum(getCookie("cartId"));
    cartId = getCookie("cartId");
  }

  util.c("cart number:", cartNum);
  util.c("cart id:", cartId);
  /* the cart number cannot renew in the session part */

  /**
   * use `reducer` instead of using useState
   */
  const cartNumReducer = (state, action) => {
    switch (action.type) {
      case "updateCartNum":
        setCartNum(cartId);
        state.cartNum = cartNum;
        return state;
      case "updateCartId":
        state.cartId = action.cartId;
        setCartNum(action.cartId);
        return state;
      case "deleteCart":
        state.cartId = null;
        setCartNum(0);
        return state;
      default:
        return state;
    }
  };

  const cartNumData = { cartId, cartNumReducer };
  const [, dispatch] = useReducer(cartNumReducer, { cartNum });

  const updateCartNum = () => dispatch({ type: "updateCartNum" });
  const updateCartId = ({ cartId }) =>
    dispatch({ type: "updateCartId", cartId });
  const deleteCart = () => dispatch({ type: "updateCartNum" });

  return (
    <CartNumContext.Provider
      value={{
        ...cartNumData,
        updateCartNum,
        updateCartId,
        deleteCart,
        cartNum,
      }}
    >
      <SessionProvider session={session}>
        <Head>
          <meta name="robots" content="noindex, nofollow" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
          {
            schema.all_structure
          }
        </Head>
        <RecoilRoot>
          <Markdown>
            <Snackbar />
            <Component {...pageProps} />
          </Markdown>
        </RecoilRoot>
      </SessionProvider>
    </CartNumContext.Provider>
  );
}
export default MyApp;

Here's a summary of what the comment is discussing:

  • The code includes a reference to the document object, which is not available during the server-side stage of a Next.js application. This can cause an error that says "Next.js: document is not defined."
  • To handle this error, the code uses a try-catch block.
  • The code also makes use of the useReducer hook, which is a way to manage state in a React application. The comment provides a link to an example of how to use this hook.
  • The comment also mentions the use of cookies in a Next.js application and provides a link to an article that discusses this topic.
  • Finally, the comment mentions skeleton loading, which is a technique used to improve the perceived performance of a website by showing a skeleton or placeholder version of the content while it is being loaded. The comment provides a link to an article that discusses how to implement this technique in a Next.js application using Tailwind CSS.

With this information in mind, you could write an article that provides an overview of these topics and explains how to use them in a Next.js application. You could start by explaining what Next.js is and why it is useful, and then delve into the specific topics mentioned in the comment, such as using try-catch blocks, the useReducer hook, cookies, and skeleton loading. You could also include code examples or other relevant resources to help readers understand and implement these concepts in their own projects.

© 2024 WOOTHINK. All Rights Reserved.
Site MapTerms and ConditionsPrivacy PolicyCookie Policy