mirror of
https://github.com/ershisan99/DevToysWeb.git
synced 2025-12-16 12:32:48 +00:00
chore: upgrade to react 19 beta and next 14 canary
This commit is contained in:
57
hooks/use-sidebar.tsx
Normal file
57
hooks/use-sidebar.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, ReactNode, useContext, useEffect, useState } from "react";
|
||||
|
||||
const LOCAL_STORAGE_KEY = "sidebar";
|
||||
|
||||
interface SidebarContext {
|
||||
isSidebarOpen: boolean;
|
||||
toggleSidebar: () => void;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||
const SidebarContext = createContext<SidebarContext | undefined>(undefined);
|
||||
|
||||
export function useSidebar() {
|
||||
const context = useContext(SidebarContext);
|
||||
if (!context) {
|
||||
throw new Error("useSidebarContext must be used within a SidebarProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
interface SidebarProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function SidebarProvider({ children }: SidebarProviderProps) {
|
||||
const [isSidebarOpen, setSidebarOpen] = useState(true);
|
||||
const [isLoading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const value = localStorage.getItem(LOCAL_STORAGE_KEY);
|
||||
if (value) {
|
||||
setSidebarOpen(JSON.parse(value) as boolean);
|
||||
}
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
const toggleSidebar = () => {
|
||||
setSidebarOpen(value => {
|
||||
const newState = !value;
|
||||
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(newState));
|
||||
return newState;
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={{ isSidebarOpen, toggleSidebar, isLoading }}>
|
||||
{children}
|
||||
</SidebarContext.Provider>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user