Gathering detailed insights and metrics for jotai-x
Gathering detailed insights and metrics for jotai-x
Jotai store factory for a best-in-class developer experience.
npm install jotai-x
Typescript
Module System
Node Version
NPM Version
97.1
Supply Chain
96.3
Quality
88.3
Maintenance
100
Vulnerability
100
License
jotai-x@2.1.1
Published on 21 Jan 2025
jotai-x@2.1.0
Published on 21 Jan 2025
jotai-x@2.0.0
Published on 15 Jan 2025
jotai-x@1.2.4
Published on 10 Jul 2024
jotai-x@1.2.3
Published on 15 Apr 2024
jotai-x@1.2.2
Published on 14 Feb 2024
TypeScript (79.28%)
JavaScript (20.72%)
Total Downloads
2,449,782
Last Day
17,236
Last Week
71,050
Last Month
304,191
Last Year
2,428,266
19 Stars
104 Commits
5 Forks
2 Watching
4 Branches
3 Contributors
Minified
Minified + Gzipped
Latest Version
2.1.1
Package Id
jotai-x@2.1.1
Unpacked Size
167.05 kB
Size
34.27 kB
File Count
8
NPM Version
10.8.2
Node Version
20.18.1
Publised On
21 Jan 2025
Cumulative downloads
Total Downloads
Last day
9%
17,236
Compared to previous day
Last week
-8.1%
71,050
Compared to previous week
Last month
13.8%
304,191
Compared to previous month
Last year
11,185.9%
2,428,266
Compared to previous year
3
JotaiX is a custom extension of Jotai, a primitive and flexible state management library for React. Jotai offers a minimalistic API to manage global, derived, or async states in React, solving common issues such as unnecessary re-renders or complex context management. JotaiX builds upon this foundation, providing enhanced utilities and patterns for more efficient and streamlined state management in larger and more complex applications.
jotai-x
, built on top of jotai
, is providing a powerful store factory
which solves these challenges, so you can focus on your app.
1yarn add jotai jotai-x
For further details and API documentation, visit jotai-x.udecode.dev.
jotai-x
?JotaiX allows for the creation of structured stores with ease, integrating seamlessly with Jotai's atom concept.
1import { createAtomStore } from 'jotai-x'; 2 3// Notice how it uses the name of the store in the returned object. 4export const { useElementStore, ElementProvider } = createAtomStore({ 5 element: null 6}, { 7 name: 'element' 8});
The createAtomStore
function simplifies the process of creating and managing atom-based states.
1createAtomStore<T extends object>(initialState: T, options?: CreateAtomStoreOptions): AtomStoreApi;
initialState
: This is an object representing the initial state of your store. Each key-value pair in this object is used to create an individual atom. This is required even if you want to set the initial value from the provider, otherwise the atom would not be created.options
: Optional. This parameter allows you to pass additional configuration options for the store creation.The options
object can include several properties to customize the behavior of your store:
name
: A string representing the name of the store, which can be helpful for debugging or when working with multiple stores.delay
: If you need to introduce a delay in state updates, you can specify it here. Optional.effect
: A React component that can be used to run effects inside the provider. Optional.extend
: Extend the store with derived atoms based on the store state. Optional.infiniteRenderDetectionLimit
: In non production mode, it will throw an error if the number of useValue
hook calls exceeds this limit during the same render. Optional.The createAtomStore
function returns an object (AtomStoreApi
) containing the following properties and methods for interacting with the store:
use<Name>Store
:
useValue
, useSet
, useState
, where values are hooks for each state defined in the store, and get
, set
, subscribe
, store
, where values are direct get/set accessors to modify each state.useValue
: Hooks for accessing a state within a component, ensuring re-rendering when the state changes. See useAtomValue.
1 const store = useElementStore(); 2 3 const element = useStoreValue('element'); 4 // alternative 5 const element = store.useElementValue(); 6 // alternative 7 const element = useElementStore().useValue('element');
useValue
supports parameters selector
, which is a function that takes the current value and returns a new value and parameter equalityFn
, which is a function that compares the previous and new values and only re-renders if they are not equal. Internally, it uses selectAtom. You must memoize selector
/equalityFn
adequately.1 const store = useElementStore();
2
3 // Approach 1: Memoize the selector yourself
4 const toUpperCase = useCallback((element) => element.toUpperCase(), []);
5 // Now it will only re-render if the uppercase value changes
6 const element = useStoreValue(store, 'element', toUpperCase);
7 // alternative
8 const element = store.useElementValue(toUpperCase);
9 // alternative
10 const element = useElementStore().useValue('element', toUpperCase);
11
12 // Approach 2: Pass an dependency array to prevent re-renders
13 const [n, setN] = useState(0); // n may change during re-renders
14 const numNthCharacter = useStoreValue(store, 'element', (element) => element[n], [n]);
15 // alternative
16 const numNthCharacter = store.useElementValue((element) => element[n], [n]);
17 // alternative
18 const numNthCharacter = store.useValue('element', (element) => element[n], [n]);
useSet
: Hooks for setting a state within a component. See useSetAtom.
1 const store = useElementStore(); 2 const element = useStoreSet(store, 'element'); 3 // alternative 4 const element = store.useSetElement(); 5 // alternative 6 const element = useElementStore().useSet('element');
useState
: Hooks for accessing and setting a state within a component, ensuring re-rendering when the state changes. See useAtom.
1 const store = useElementStore(); 2 const element = useStoreState(store, 'element'); 3 // alternative 4 const element = store.useElementState(); 5 // alternative 6 const element = useElementStore().useState('element');
get
: Directly get the state. Not a hook so it could be used in event handlers or other hooks, and the component won't re-render if the state changes. See createStore
1 const store = useElementStore(); 2 useEffect(() => { console.log(store.getElement()) }, []); 3 // alternative 4 useEffect(() => { console.log(store.get('element')) }, []);
set
: Directly set the state. Not a hook so it could be used in event handlers or other hooks. See createStore
1 const store = useElementStore(); 2 useEffect(() => { store.setElement('div') }, []); 3 // alternative 4 useEffect(() => { store.set('element', 'div') }, []);
subscribe
: Subscribe to the state change. . See createStore
1 const store = useElementStore(); 2 useEffect(() => store.subscribeElement((newElement) => console.log(newElement)), []); 3 // alternative 4 useEffect(() => store.subscribe('element', (newElement) => console.log(newElement)), []);
store
: The JotaiStore for the current context.
1 const store = useElementStore(); 2 const jotaiStore = store.store;
<Name>Provider
:
<name>Store
:
atom
: Access the atoms used by the store, including derived atoms defined using extend
. See atom.createAtomStore
generates a provider component (<Name>Provider
) for a Jotai store. This provider not only supplies the store to its child components but also handles hydrating and syncing the store's state. Here's how it works:
initialValues
prop.<state>
props: there is one for each state defined in the store.JotaiX creates scoped providers, enabling more granular control over different segments of state within your application. createAtomStore
sets up a context for each store, which can be scoped using the scope
prop. This is particularly beneficial in complex applications where nested providers are needed.
There are two ways of creating derived atoms from your JotaiX store.
extend
Atoms defined using the extend
option are made available in the same places as other values in the store.
1const { useUserStore } = createAtomStore({ 2 username: 'Alice', 3}, { 4 name: 'user', 5 extend: (atoms) => ({ 6 intro: atom((get) => `My name is ${get(atoms.username)}`), 7 }), 8}); 9 10const userStore = useUserStore(); 11const intro = userStore.useIntroValue();
Derived atoms can also be defined externally by accessing the store's atoms through the <name>Store
API. Externally defined atoms can be accessed through the store using special hooks:
useAtomValue
, useSetAtom
, useAtomState
, getAtom
, setAtom
, subscribeAtom
.
1const { userStore, useUserStore } = createAtomStore({ 2 username: 'Alice', 3}, { name: 'user' }); 4 5const introAtom = atom((get) => `My name is ${get(userStore.atom.username)}`); 6 7const userStore = useUserStore(); 8const intro = userStore.useAtomValue(introAtom);
1import { createAtomStore } from 'jotai-x'; 2 3export type AppStore = { 4 name: string; 5 onUpdateName: (name: string) => void; 6}; 7 8const initialState: Nullable<AppStore> = { 9 name: null, 10 onUpdateName: null, 11}; 12 13export const { useAppStore, AppProvider } = createAtomStore( 14 initialState as AppStore, 15 { name: 'app' } 16);
1// ... 2 3const App = () => { 4 return ( 5 <AppProvider 6 initialValues={{ 7 onUpdateName: (name: string) => console.log(name) 8 }} 9 // Either here or in initialValues 10 name="John Doe" 11 > 12 <Component /> 13 </AppProvider> 14 ); 15}; 16 17const Component = () => { 18 const appStore = useAppStore(); 19 const [name, setName] = store.useNameState(); 20 const onUpdateName = store.useOnUpdateNameValue(); 21 22 useEffect(() => store.subscribe.name((newName) => { 23 console.log(`Name updated to: ${newName}`); 24 // An alternative to `appStore.useNameState()`, won't rerender when the state changes 25 assert.ok(newName === appStore.getName()); 26 if (newName.includes('#')) { 27 // Equivalent to `appStore.useSetName()`'s return 28 appStore.setName('invalid'); 29 onUpdateName('invalid'); 30 } 31 }), [appStore]) 32 33 return ( 34 <div> 35 <input value={name} onChange={(e) => setName(e.target.value)} /> 36 <button onClick={() => onUpdateName(name)}>Update</button> 37 </div> 38 ); 39};
1const App = () => { 2 return ( 3 // Parent scope 4 <AppProvider 5 scope="parent" 6 initialValues={{ 7 onUpdateName: (name: string) => console.log("Parent:", name) 8 }} 9 name="Parent User" 10 > 11 <div> 12 <h1>Parent Component</h1> 13 <Component /> 14 {/* Child scope */} 15 <AppProvider 16 scope="child" 17 initialValues={{ 18 onUpdateName: (name: string) => console.log("Child:", name) 19 }} 20 name="Child User" 21 > 22 <div> 23 <h2>Child Component</h2> 24 <Component /> 25 </div> 26 </AppProvider> 27 </div> 28 </AppProvider> 29 ); 30}; 31 32// Accessing state from the specified scope. 33const Component = () => { 34 // Here, we get the state from the parent scope 35 const parentAppStore = useAppStore('parent'); 36 const [name, setName] = parentScope.useNameState(); 37 // Here, we get the state from the closest scope (default) 38 const appStore = useAppStore(); 39 const onUpdateName = appStore.useOnUpdateNameValue(); 40 41 return ( 42 <div> 43 <input value={name || ''} onChange={(e) => setName(e.target.value)} /> 44 <button onClick={() => onUpdateName(name)}>Update Name</button> 45 </div> 46 ); 47};
num
times in the same renderWhen calling use<Key>Value
or useValue
with selector
and equalityFn
, those two functions must be memoized. Otherwise, the component will re-render infinitely. In order to prevent developers from making this mistake, in non-production mode (process.env.NODE_ENV !== 'production'
), we will throw an error if the number of useValue
hook calls exceeds a certain limit.
Usually, this error is caused by not memoizing the selector
or equalityFn
functions. To fix this, you can use useCallback
to memoize the functions, or pass a dependency array yourselves. We support multiple alternatives:
1// No selector at all 2useValue('key') 3 4// Memoize with useCallback yourself 5const memoizedSelector = useCallback(selector, [...]); 6const memoizedEqualityFn = useCallback(equalityFn, [...]); 7// memoizedEqualityFn is an optional parameter 8useValue('key', memoizedSelector, memoizedEqualityFn); 9 10// Provide selector and its deps 11useValue('key', selector, [...]); 12 13// Provide selector and equalityFn and all of their deps 14useValue('key', selector, equalityFn, [...]);
The error could also be a false positive, since the internal counter is shared across all useValue
calls of the same store. If your component tree is very deep and uses the same store's useValue
multiple times, then the limit could be reached. To deal with that, createAtomStore
supports an optional parameter infiniteRenderDetectionLimit
. You can configure that with a higher limit.
use<Name>Store
: get
is renamed to use<Key>Value
, set
is renamed to useSet<Key>
, use
is renamed to useState
.1- const name = useAppStore().get.name(); 2- const setName = useAppStore().set.name(); 3- const [name, setName] = useAppStore().use.name(); 4 5+ const appStore = useAppStore(); 6+ const name = appStore.useNameValue(); 7+ const setName = appStore.useSetName(); 8+ const [name, setName] = appStore.useNameState(); 9 10+ // alternative 11+ const name = appStore.useValue('name'); 12+ const setName = appStore.useSet('name'); 13+ const [name, setName] = appStore.useState('name');
.atom()
APIs:1- const atomValue = useAppStore().get.atom(atomConfig); 2- const setAtomValue = useAppStore().set.atom(atomConfig); 3- const [atomValue, setAtomValue] = useAppStore().use.atom(atomConfig); 4 5+ const appStore = useAppStore(); 6+ const atomValue = appStore.useAtomValue(atomConfig); 7+ const setAtomValue = appStore.useSetAtom(atomConfig); 8+ const [atomValue, setAtomValue] = appStore.useAtomState(atomConfig);
NOTE: Try to avoid using the key "atom" as the store state key because
useValue('atom')
and useSet('atom')
and useState('atom')
are not supported. They are only valid if the key "atom" is presented in the store.
On the other hand, useAtomValue()
, useSetAtom()
, and useAtomState()
cannot access the state if the key "atom" is presented in the store.
Return of use<Name>Store
: store
is no longer a function. Now it is a direct property.
1- const store = useAppStore().store(); 2 3+ const appStore = useAppStore(); 4+ const jotaiStore = appStore.store;
use<Name>Store
: option
is no longer a valid parameter of useValue
and useSet
. To control the behavior, directly pass the options to createAtomStore
or use<Name>Store
.1- const scope1Name = useAppStore().useValue.name(scope1Options); 2- const scope2Name = useAppStore().useValue.name(scope2Options); 3 4+ const scope1AppStore = useAppStore(scope1Options); 5+ const scope1Name = scope1AppStore.useNameValue(); 6+ const scope2AppStore = useAppStore(scope2Options); 7+ const scope2Name = scope2AppStore.useNameValue();
Discussions is the best place for bringing opinions and contributions. Letting us know if we're going in the right or wrong direction is great feedback and will be much appreciated!
🌟 Stars and 📥 Pull requests are welcome! Don't hesitate to share your feedback here. Read our contributing guide to get started.
No vulnerabilities found.
No security vulnerabilities found.