Region React Context in Storefront
In this guide, you'll learn how to create a region context in your React storefront.
Why Create a Region Context?#
Throughout your storefront, you'll need to access the customer's selected region to perform different actions, such as retrieve product's prices in the selected region.
So, if your storefront is React-based, create a region context and add it at the top of your components tree. Then, you can access the selected region anywhere in your storefront.
Create Region Context Provider#
For example, create the following file that exports a RegionProvider component and a useRegion hook:
1"use client" // include with Next.js 13+2 3import { 4 createContext, 5 useContext, 6 useEffect, 7 useState,8} from "react"9import { HttpTypes } from "@medusajs/types"10import { sdk } from "@/lib/sdk"11 12type RegionContextType = {13 region?: HttpTypes.StoreRegion14 setRegion: React.Dispatch<15 React.SetStateAction<HttpTypes.StoreRegion | undefined>16 >17}18 19const RegionContext = createContext<RegionContextType | null>(null)20 21type RegionProviderProps = {22 children: React.ReactNode23}24 25export const RegionProvider = ({ children }: RegionProviderProps) => {26 const [region, setRegion] = useState<27 HttpTypes.StoreRegion28 >()29 30 useEffect(() => {31 if (region) {32 // set its ID in the local storage in33 // case it changed34 localStorage.setItem("region_id", region.id)35 return36 }37 38 const regionId = localStorage.getItem("region_id")39 if (!regionId) {40 // retrieve regions and select the first one41 sdk.store.region.list()42 .then(({ regions }) => {43 setRegion(regions[0])44 })45 } else {46 // retrieve selected region47 sdk.store.region.retrieve(regionId)48 .then(({ region: dataRegion }) => {49 setRegion(dataRegion)50 })51 }52 }, [region])53 54 return (55 <RegionContext.Provider value={{56 region,57 setRegion,58 }}>59 {children}60 </RegionContext.Provider>61 )62}63 64export const useRegion = () => {65 const context = useContext(RegionContext)66 67 if (!context) {68 throw new Error("useRegion must be used within a RegionProvider")69 }70 71 return context72}
The RegionProvider handles retrieving the selected region from the Medusa application, and updating its ID in the localStorage.
The useRegion hook returns the value of the RegionContext. Child components of RegionProvider use this hook to access region or setRegion.
Use RegionProvider in Component Tree#
To use the region context's value, add the RegionProvider high in your component tree.
For example, if you're using Next.js, add it to the app/layout.tsx or src/app/layout.tsx file:
Use useRegion Hook#
Now, you can use the useRegion hook in child components of RegionProvider.
For example: