Last active
December 11, 2025 02:40
-
-
Save HugeLetters/357f47358400e1e4c70aacddbd8a5cf5 to your computer and use it in GitHub Desktop.
Dynamic Delcarative Header
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { contentStackAtom } from "@/hooks/useHeader"; | |
| import { useAtomValue } from "jotai"; | |
| export default function Header() { | |
| const stack = useAtomValue(contentStackAtom).filter((node) => !!node.content); | |
| return ( | |
| <header> | |
| {stack.at(-1)?.content ?? "App Title"} | |
| </header> | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { immerAtom } from "@/utils/immer"; | |
| import { useSetAtom } from "jotai"; | |
| import { useEffect, useId, type ReactNode } from "react"; | |
| export default function useHeader(content: ReactNode): void { | |
| const setContentStack = useSetAtom(contentStackAtom); | |
| const id = useId(); | |
| useEffect(() => { | |
| setContentStack((x) => { | |
| const current = x.find((x) => x.id === id); | |
| if (!current) { | |
| x.push({ content, id }); | |
| return; | |
| } | |
| current.content = content; | |
| }); | |
| }, [id, setContentStack, content]); | |
| useEffect(() => { | |
| return () => { | |
| setContentStack((x) => x.filter((x) => x.id !== id)); | |
| }; | |
| }, [id, setContentStack]); | |
| } | |
| export const contentStackAtom = immerAtom<Array<{ content: ReactNode; id: string }>>([]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, I found an interesting, simpler way to teleport components around. Check it out
facebook/react#12615 (comment)