Skip to content

Commit

Permalink
fix: memoize the sidebar context provider's value (#408)
Browse files Browse the repository at this point in the history
  • Loading branch information
stefl authored Nov 28, 2024
1 parent dbe04fd commit 60ee010
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
37 changes: 22 additions & 15 deletions apps/nextjs/src/lib/hooks/use-sidebar.tsx
Original file line number Diff line number Diff line change
@@ -1,55 +1,62 @@
"use client";

import * as React from "react";
import {
createContext,
useContext,
useMemo,
useState,
useEffect,
useCallback,
} from "react";

const LOCAL_STORAGE_KEY = "sidebar";

interface SidebarContext {
export interface SidebarContext {
isSidebarOpen: boolean;
toggleSidebar: () => void;
isLoading: boolean;
}

const SidebarContext = React.createContext<SidebarContext | undefined>(
undefined,
);
const SidebarContext = createContext<SidebarContext | undefined>(undefined);

export function useSidebar() {
const context = React.useContext(SidebarContext);
const context = useContext(SidebarContext);
if (!context) {
throw new Error("useSidebarContext must be used within a SidebarProvider");
}
return context;
}

interface SidebarProviderProps {
export interface SidebarProviderProps {
readonly children: React.ReactNode;
}

export function SidebarProvider({ children }: SidebarProviderProps) {
const [isSidebarOpen, setSidebarOpen] = React.useState(false);
const [isLoading, setLoading] = React.useState(true);
const [isSidebarOpen, setSidebarOpen] = useState(false);
const [isLoading, setLoading] = useState(true);

React.useEffect(() => {
useEffect(() => {
const value = localStorage.getItem(LOCAL_STORAGE_KEY);
if (value) {
setSidebarOpen(false);
}
setLoading(false);
}, []);

const toggleSidebar = () => {
const toggleSidebar = useCallback(() => {
setSidebarOpen((value) => {
const newState = !value;
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(newState));
return newState;
});
};
}, [setSidebarOpen]);

const contextValue = useMemo(() => {
return { isSidebarOpen, toggleSidebar, isLoading };
}, [isSidebarOpen, isLoading, toggleSidebar]);

return (
<SidebarContext.Provider
value={{ isSidebarOpen, toggleSidebar, isLoading }}
>
<SidebarContext.Provider value={contextValue}>
{children}
</SidebarContext.Provider>
);
Expand Down
1 change: 0 additions & 1 deletion packages/exports/src/gSuite/docs/populateDoc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import type { docs_v1 } from "@googleapis/docs";
import type { Result } from "../../types";
import type { ValueToString } from "../../utils";
import { defaultValueToString } from "../../utils";
import { processImageReplacements } from "./processImagesReplacements";
import { textReplacements } from "./textReplacements";

/**
Expand Down

0 comments on commit 60ee010

Please sign in to comment.