The "shared state" is a React state that shares the same value across the
entire app. Users declare a shared state constant that can be reused across
multiple components with the same underlying value.
Shared states provide persistence to local storage and/or indexed DB out of
the box, by using "@choksheak/ts-utils". Note that no matter if the shared
state uses persistence or not, it will always maintain a copy of the state
in memory. Persisted values can be configured with an automatic expiration
duration.
This module is largely similar to the open source "jotai" npm library. You
can use shared states to replace "jotai" in your code, and optionally make
use of the persistence mechanism. A quick migration guide from jotai is:
// Create a new shared state in the top level scope. // The first argument is the default value, which is required. // The second argument is an options object, and is optional (defaults // to storing in memory only without any persistence). constusersState = sharedState( [], { store: { persistTo:"indexedDb", key:"users" }} );
exportconstUsersComponent: React.FC = () => { // Get both the value and the setter. const [users, setUsers] = useSharedState(usersState); ... };
exportconstReadOnlyComponent: React.FC = () => { // Get the value only. constusers = useSharedStateValue(usersState); ... };
exportconstWriteOnlyComponent: React.FC = () => { // Get the setter only. constsetUsers = useSharedStateSetter(usersState); ... };
The "shared state" is a React state that shares the same value across the entire app. Users declare a shared state constant that can be reused across multiple components with the same underlying value.
Shared states provide persistence to local storage and/or indexed DB out of the box, by using "@choksheak/ts-utils". Note that no matter if the shared state uses persistence or not, it will always maintain a copy of the state in memory. Persisted values can be configured with an automatic expiration duration.
This module is largely similar to the open source "jotai" npm library. You can use shared states to replace "jotai" in your code, and optionally make use of the persistence mechanism. A quick migration guide from jotai is:
Example: