Region React Context in the Storefront

Share the selected region across React components.

On this page

In this guide, you'll learn how to share the selected region in a React storefront.

Do not keep the region in localStorage or a client context that fetches in useEffect.

On Next.js:

  • The URL [countryCode] is the customer's country.
  • Server modules call getRegion(storeCode, countryCode).
  • Product list/retrieve pass region_id so prices calculate.
  • Changing country is a navigation to a new [countryCode], which updates the cart region via getOrSetCart.

See Store Selected Region and Build a Next.js Storefront.

A client country switcher can still be a dropdown; it should router.push to the new country path, not write region_id to localStorage.


SPA: Region Context Provider

If you're building a client-rendered SPA, a context at the top of the tree can hold the selected region.

tsx

tsxCopy
"use client"
import {
createContext,
useContext,
useEffect,
useState,
} from "react"
import { HttpTypes } from "@aiminaabeejs/types"
import { sdk } from "@/lib/sdk"
type RegionContextType = {
region?: HttpTypes.StoreRegion
setRegion: React.Dispatch<
React.SetStateAction<HttpTypes.StoreRegion | undefined>
>
}
const RegionContext = createContext<RegionContextType | null>(null)
export const RegionProvider = ({ children }: { children: React.ReactNode }) => {
const [region, setRegion] = useState<HttpTypes.StoreRegion>()
useEffect(() => {
if (region) {
return
}
sdk.store.region.list(storeCode)
.then(({ regions }) => {
setRegion(regions[0])
})
}, [region])
return (
<RegionContext.Provider value={{ region, setRegion }}>
{children}
</RegionContext.Provider>
)
}
export const useRegion = () => {
const context = useContext(RegionContext)
if (!context) {
throw new Error("useRegion must be used within a RegionProvider")
}
return context
}

Add RegionProvider high in the tree. Child components call useRegion() for region and setRegion.