Skip to content

Instantly share code, notes, and snippets.

@3p3r
Created April 2, 2026 17:19
Show Gist options
  • Select an option

  • Save 3p3r/95aea2bcde94727fbf3d0b21cc967375 to your computer and use it in GitHub Desktop.

Select an option

Save 3p3r/95aea2bcde94727fbf3d0b21cc967375 to your computer and use it in GitHub Desktop.
react context stuff
// src/context/WorkspaceContext.tsx
'use client';
import { createContext, useContext, useState, ReactNode } from 'react';
type WorkspaceName = {
name: "guard" | "watchtower";
};
type WorkspaceContextType = {
workspace: WorkspaceName;
setWorkspace: (newWorkspace: WorkspaceName) => void;
};
// Create Context
const WorkspaceContext = createContext<WorkspaceContextType | undefined>(undefined);
// Provider Component (receives only `children` prop)
export function WorkspaceProvider({ children }: { children: ReactNode }) {
const [workspace, setWorkspace] = useState<WorkspaceName>({
name: "guard"
});
return (
<WorkspaceContext.Provider value={{ workspace, setWorkspace }}>
{children}
</WorkspaceContext.Provider>
);
}
// Custom hook to use the context
export const useWorkspace = () => {
const context = useContext(WorkspaceContext);
if (context === undefined) {
throw new Error('useWorkspace must be used within a WorkspaceProvider');
}
return context;
};
// ---------------------------------------------
// app/layout.tsx
import type { Metadata } from 'next';
import { WorkspaceProvider } from '@/context/WorkspaceContext';
export const metadata: Metadata = {
title: 'Workspace App',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<WorkspaceProvider>
{children}
</WorkspaceProvider>
</body>
</html>
);
}
// ---------------------------------------------
// app/page.tsx
'use client';
import { useWorkspace } from '@/context/WorkspaceContext';
export default function Home() {
const { workspace, setWorkspace } = useWorkspace();
const switchToWatchtower = () => {
setWorkspace({ name: "watchtower" });
};
const switchToGuard = () => {
setWorkspace({ name: "guard" });
};
return (
<div style={{ padding: '2rem' }}>
<h1>Current Workspace: {workspace.name}</h1>
<div style={{ marginTop: '20px' }}>
<button onClick={switchToGuard} style={{ marginRight: '10px' }}>
Switch to Guard
</button>
<button onClick={switchToWatchtower}>
Switch to Watchtower
</button>
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment