Work With useContext

The Context API is a state management library for Next.js applications that provides a straightforward way to share state between components. By using a global context object, it allows components to access and update shared state throughout the application via the useContext hook.

How to Use useContext?

Here’s a breakdown of setting up and using useContext in SaasCart.

Step 1: Create Context

File: index.jsx

index.jsx
import { createContext } from 'react'; 

const AccountContext = createContext();
export default AccountContext;
AccountProvider.jsx
import React, { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import AccountContext from '.';
import request from '../../Utils/AxiosUtils';
import { useCookies } from 'react-cookie';
import { SelfAPI } from '@/Utils/AxiosUtils/API';

const AccountProvider = (props) => {
  const [cookies] = useCookies(['uat']);
  const [mobileSideBar, setMobileSideBar] = useState(false)
  const { data, refetch, isLoading } = useQuery([SelfAPI], () => request({ url: SelfAPI }), {
    enabled: false,
    select: (res) => {
      return res?.data;
    },
  });
  const [accountData, setAccountData] = useState();

  useEffect(() => {
    cookies.uat && refetch();
  }, [cookies.uat]);

  useEffect(() => {
    if (data) {
      setAccountData(data);
    }
  }, [isLoading, data]);

  return {props.children};
};
                    
export default AccountProvider;

The account provider is wrapped in the main layout component so that it is available to other components.

MainLayout.jsx
"use client";
import AccountProvider from "@/Helper/AccountContext/AccountProvider";
import SubLayout from "./SubLayout";

const MainLayout = ({ children }) => {
  return (
    <AccountProvider>
      <SubLayout children={children} />
    </AccountProvider>
  );
};

export default MainLayout;

This is a file example of how to utilise the useContext in the saascart.

AddressHeader.jsx
import AccountContext from "@/Helper/AccountContext";
import { useContext, useEffect, useState } from "react";
import AddressData from "./AddressData";

const AddressHeader = () => {
  const [addressState, setAddressState] = useState([]);
  const { accountData, refetch } = useContext(AccountContext);
  useEffect(() => {
    accountData?.address.length > 0 &&
      setAddressState((prev) => [...accountData?.address]);
  }, [accountData]);

  return (
    <>
    <AddressData>
          addressState={addressState}
          setAddressState={setAddressState}
        />
    
  );
};

export default AddressHeader;