"Portaling" a writable atom #699
Replies: 3 comments
-
At a glance, I wasn't able to get the point, but the codesandbox example helped. (Does "Deselect" button work as expected?) Not sure if I understand fully, but I guess I like the idea generally:
Overall, it looks interesting. Nothing seems wrong from jotai lib perspective, and it can be a powerful practice. |
Beta Was this translation helpful? Give feedback.
-
thank you for your feedbacks! |
Beta Was this translation helpful? Give feedback.
-
https://docs.pmnd.rs/jotai/guides/atoms-in-atom
function TextElement() {
const [selection, setSelection] = useAtom(selectionAtom);
const wrap = useAtomPortal(selection === "text", portalAtom, deselectTextAtom); // no useEffect
return (
<>
Text element {selection === "text" ? "selected" : "not selected"}
<button onClick={() => wrap(setSelection)("text")}>Select text</button>
</>
);
} not sure how it works, just something without useEffect, which mean you invoke in the callback somehow. |
Beta Was this translation helpful? Give feedback.
-
I've recently enjoyed using React.Portal quite a bit, especially in the context of a design tool with many different types of elements, with the strategy described in this blog post: https://jjenzz.com/avoid-global-state-colocate
this allows me to structure my code in a way where, e.g. TextElement can render "remotely" into main application layouts based on its state:
super handy, quick for prototyping, no need for a big
switch/case
statement inside Inspector that I have to manageso I have run into a situation with jotai where this pattern could make sense? made a proof of concept (linked below) but just wanted to share here to get @dai-shi 's thoughts? https://codesandbox.io/s/headless-smoke-s5viy?file=/src/App.tsx
example problem:
API might look like
i'm aware i could do this with a switch/case in a central deselect writable atom, but just curious if there's an interesting pattern here. is there a better way i could do something like this?
here's a codesandbox of this in action: https://codesandbox.io/s/headless-smoke-s5viy?file=/src/App.tsx
Beta Was this translation helpful? Give feedback.
All reactions