While Atom Selectors are great for simple, inexpensive logic, they lack fine-grained control over re-evaluation. For complex, expensive operations (like sorting or filtering large lists), use Ions.
Ions are special atoms created with the ion() factory. They receive an AtomGetters object as their first parameter, allowing them to behave like atoms while being specifically designed for selector-type operations.
When to use an Ion instead of an Atom Selector:
- To memoize expensive calculations.
- To run side effects on state change.
- To trigger React Suspense.
- When you need any other atom-specific capabilities.
import { ion } from '@zedux/react'
// An ion that filters and sorts users based on a role
const sortedUsersAtom = ion('sortedUsers', ({ get }, roleFilter: string) => {
const users = get(usersAtom).filter(user => user.role === roleFilter)
return [...users].sort((userA, userB) => userA.name.localeCompare(userB.name))
})
function MyComponent() {
// Access ions just like regular atoms
const adminUsers = useAtomValue(sortedUsersAtom, ['admin'])
}