App Provider
A context provider to manage application-wide state including direction, theme, and sidebar visibility using cookies.
Overview
AppProvider is a React context provider component used to manage application-level preferences such as UI direction (ltr or rtl), theme (dark, light, or system), and sidebar visibility. It also provides utility methods to manage cookies for persisting user preferences across sessions.
Behavior
- Uses internal state to manage the open/closed status of the sidebar.
- Initializes UI direction using the
useDirectionhook. - Provides methods to set cookies with expiration defaults:
setCookie: saves a cookie for 30 days by default.
Example
app/layout.tsx
import { userAgent } from "next/server";
import { headers, cookies } from "next/headers";
import { AppProvider } from "@/config/app-context";
import { ThemeProvider } from "@/config/themes";
import { Cookies, Theme } from "@/config/types";
async function cookiesValues() {
const cookiesStore = await cookies();
return {
dir: cookiesStore.get(Cookies.dir)?.value as Direction,
theme: cookiesStore.get(Cookies.theme)?.value as Theme,
isOpenAside: (cookiesStore.get(Cookies.isOpenAside)?.value === "true") as boolean
};
}
export default async function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
const [headersList, cookieStore] = await Promise.all([headers(), cookiesValues()]);
const ua = userAgent({ headers: headersList });
return (
<AppProvider userAgent={ua} {...cookieStore}>
<html lang="en" dir={cookieStore.dir} suppressHydrationWarning>
<body>
<ThemeProvider>{children}</ThemeProvider>
</body>
</html>
</AppProvider>
);
}Source Codes
Full working code example, including necessary markup and styles. You can copy and paste this code directly to start using the component immediately.