@reatom/react package provides seamless integration between Reatom and React, offering hooks and utilities for using atoms in React components.
Installation
This package requires React 18.2.0 or higher.
Setup
Wrap your application with the Reatom context provider to make the frame available to all components:Core Hooks
useAtom
The primary hook for working with atoms in React components. It supports multiple use cases:Reading and Writing Atoms
Creating Local State
You can create component-local atoms by passing a primitive value:Using Computed Values
Pass a function to create a computed atom:API Reference
target: An atom, primitive value, or computed functiondeps: Optional dependency array (likeuseMemo)options: Optional configurationname: Debug name for the atomsubscribe: Whether to subscribe to changes (default:true)
[state, setState?, atom, frame]: Tuple containing:- Current state value
- Optional setter function (undefined for computed atoms)
- The atom instance
- The current frame
useAction
Wrap functions to execute them within the Reatom context:target: Function to wrap or existing actiondeps: Dependency arrayname: Optional debug name
- Stable callback function that executes within the Reatom context
useFrame
Get the current Reatom frame from context:Advanced Components
reatomComponent
Create optimized components that automatically track atom dependencies:- Automatic subscription management
- Fine-grained reactivity
- Better performance for complex state
reatomFactoryComponent
Create components with initialization logic that runs only once:Form Binding
bindField
Bind form fields to Reatom atoms with validation support:bindField helper returns an object with:
valueorchecked: Current field valueonChange: Change handleronBlur: Blur handleronFocus: Focus handlererror: Validation error message
Best Practices
1
Use useAtom for simple cases
For most use cases,
useAtom provides the simplest API.2
Leverage reatomComponent for performance
When dealing with complex state or many atoms,
reatomComponent offers better performance through automatic dependency tracking.3
Memoize dependencies properly
When using computed functions with
useAtom, ensure your dependency array is correct to avoid unnecessary recalculations.4
Use useAction for stable callbacks
Wrap event handlers with
useAction to ensure they execute in the correct Reatom context and maintain stable references.TypeScript Support
The package is fully typed and provides excellent TypeScript support:Suspense Support
Reatom React integration supports React Suspense for async operations:Next Steps
- Explore Core Concepts to learn more about atoms
- Check out [Asynchttps://github.com/reatom/reatom/tree/main/packages for handling asynchronous state
- Learn about [Formshttps://github.com/reatom/reatom/tree/main/packages for advanced form management