[Tips] useSelector equivalent
See original GitHub issueWhile the atom model fits with bottom-up approach (composing small atoms), we could create a big atom and select pieces out of it.
const bigAtom = atom({
num: 0,
str: 'hi',
bool: true,
obj: { a: 1, b: 2, arr: [3, 4, 5] },
})
const numAtom = atom(
get => get(bigAtom).num,
(get, set, update) => {
const prev = get(bigAtom)
const num = typeof update === 'function' ? update(prev.num) : update
set(bigAtom, { ...prev, num })
}
)
const [num, setNum] = useAtom(numAtom)
We can make this a hook. Let’s try for a read-only atom.
const useSelector = (anAtom, selector) => {
const selectedAtom = useMemo(() => atom(get => selector(get(anAtom))), [anAtom, selector])
return useAtom(selectedAtom)[0]
}
Issue Analytics
- State:
- Created 3 years ago
- Reactions:5
- Comments:6 (4 by maintainers)
Top Results From Across the Web
UseSelector and UseDispatch: A Guide to React-Redux Hooks
This guide will cover how to implement the React-Redux hooks useSelector and ... The equivalent of map state to props is useSelector.
Read more >Implement useSelector equivalent for React Context?
So my question is: can a hook like useSelector be created that would grab a piece of the context instead of the Redux...
Read more >React-Redux Hooks: useSelector and useDispatch
The equivalent of map state to props is useSelector . It takes in a function argument that returns the part of the state...
Read more >Hooks - React Redux
Call useSelector() multiple times, with each call returning a single field value · Use Reselect or a similar library to create a memoized ......
Read more >Redux-less context-based useSelector hook that has same ...
The benchmark code for useSelector is almost identical among three libraries. The code for useTrackedState is also identical between two ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
No, your useNumValue updates only if num is changed. This is because the useSelector creates a new derived atom in it. Happy to help you for better understanding.
btw, useSelector requires useCallack for selector
Or, define the selector outside render.
useSelector here is just to show the possibility, and I’m not sure if there’re real use cases.
Yes, the derived atoms work like recoil’s selector. They are only recalculated if one or more of its dependencies change.