Build Jotai-style atoms: derived atoms with dynamic dependencies, batched writes, mounting and React hooks
Problem
Jotai and Recoil model state as atoms: small units of state, plus derived atoms computed from others. Components read exactly the atoms they need and re-render only when those change. Interviewers like it because a correct store has to solve the classic reactive problems: dependencies that change between runs, diamonds that must not show half-updated values, and work that should stop when nobody is watching. Build the core of Jotai and its React hooks.
const price = atom(100);
const qty = atom(2);
const total = atom((get) => get(price) * get(qty));
const store = createStore();
store.sub(total, () => console.log(store.get(total)));
store.set(qty, 3); // logs 300Ref. UR-1438 · © UIRound · uiround.com/questions/build-jotai-style-atoms-derived-atoms-with-dynamic-dependencies-batched-writes-mounting-and-react-hooks
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 5
- edge cases
- 4
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1An atom is only a config object; the store holds the values. For a derived atom, the store needs to know which atoms its last run read, and whether any of them has changed since.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.