All Projects β†’ immobiliare β†’ atomic-state

immobiliare / atomic-state

Licence: MIT License
A decentralized state management library for React

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to atomic-state

react-cool-form
😎 πŸ“‹ React hooks for forms state and validation, less code more performant.
Stars: ✭ 246 (+355.56%)
Mutual labels:  hooks, state-management, state, react-hooks
jedisdb
redis like key-value state management solution for React
Stars: ✭ 13 (-75.93%)
Mutual labels:  hooks, state-management, state, react-hooks
eventrix
Open-source, Predictable, Scaling JavaScript library for state managing and centralizing application global state. State manage system for react apps.
Stars: ✭ 35 (-35.19%)
Mutual labels:  hooks, state-management, state
temperjs
State management for React, made simple.
Stars: ✭ 15 (-72.22%)
Mutual labels:  state-management, state, recoiljs
useSharedState
useSharedState is a simple hook that can be used to share state between multiple React components.
Stars: ✭ 0 (-100%)
Mutual labels:  hooks, state-management, state
Pullstate
Simple state stores using immer and React hooks - re-use parts of your state by pulling it anywhere you like!
Stars: ✭ 683 (+1164.81%)
Mutual labels:  hooks, state-management, state
Use Global Context
A new way to use β€œuseContext” better
Stars: ✭ 34 (-37.04%)
Mutual labels:  hooks, state-management, state
rex-state
Convert hooks into shared states between React components
Stars: ✭ 32 (-40.74%)
Mutual labels:  state-management, state, react-hooks
use-app-state
🌏 useAppState() hook. that global version of setState() built on Context.
Stars: ✭ 65 (+20.37%)
Mutual labels:  hooks, state-management, react-hooks
concave
🧐 Lens-like state management (for React).
Stars: ✭ 13 (-75.93%)
Mutual labels:  state-management, state, react-hooks
use-query-string
πŸ†™ A React hook that serializes state into the URL query string
Stars: ✭ 50 (-7.41%)
Mutual labels:  hooks, state-management, react-hooks
Easy Peasy
Vegetarian friendly state for React
Stars: ✭ 4,525 (+8279.63%)
Mutual labels:  hooks, state-management, react-hooks
Constate
React Context + State
Stars: ✭ 3,519 (+6416.67%)
Mutual labels:  hooks, state-management, react-hooks
Pure Store
A tiny immutable store with type safety.
Stars: ✭ 133 (+146.3%)
Mutual labels:  hooks, state-management, state
Effector
The state manager β˜„οΈ
Stars: ✭ 3,572 (+6514.81%)
Mutual labels:  state-management, state, state-manager
resynced
An experimental hook that lets you have multiple components using multiple synced states using no context provider
Stars: ✭ 19 (-64.81%)
Mutual labels:  hooks, state-management, react-hooks
particule
Fine-grained atomic React state management library
Stars: ✭ 31 (-42.59%)
Mutual labels:  state-management, state, recoil
entangle
Global state management tool for react hooks inspired by RecoilJS and Jotai using proxies.
Stars: ✭ 26 (-51.85%)
Mutual labels:  hooks, state-management, recoiljs
useAudioPlayer
Custom React hook & context for controlling browser audio
Stars: ✭ 176 (+225.93%)
Mutual labels:  hooks, react-hooks
useStateMachine
The <1 kb state machine hook for React
Stars: ✭ 2,231 (+4031.48%)
Mutual labels:  hooks, state-management

AtomicState

CI code style: prettier Commitizen friendly bundlephobia

A decentralized state management library for React

Sometimes when you have to share some state between components you also add some complexity to it (lifting the state up, adding a context or dirtying your global state manager).

AtomicState brings to you a way to share state in a simple and decentralized way without burdening your app size and complexity.

Features Highlights

  • πŸ’‘ Simple & Reactish: Use AtomicState without learning new concepts because it works like the React API that you already know
  • πŸ’‘ Small footprint: AtomicState wieghts only 1.5Kb (gzip) on your production bundle
  • πŸ’‘ SSR ready: Server Side Rendering is a first-class citizen for AtomicState and it works like a breeze
  • πŸ’‘ Integrated DevTools: Install the official devtools from the Chrome Web Store and take a look in your atoms!
  • πŸ’‘ Decentralized: The state atoms can be loaded only when they are needed enabling you to do lazy load without troubles.

Table of contents

Quick start

Sharing some state across components sometimes is more complex than it should be.

With AtomicState it will be clean and simple:

./doYouKnowAtomicState.js

import { createStateAtom } from '@immobiliarelabs/atomic-state';

// This is an atom a container for a piece of state
export const doYouKnowAtomicState = createStateAtom({
    key: `DoYoyKnowAtomicState`, // unique ID
    default: null, // default value (aka initial value)
});

By importing the created atom you can read and modify the state wherever you want:

./DoYoyKnowAtomicStateDisclamer.js

import { useStateAtom } from '@immobiliarelabs/atomic-state';
import { doYouKnowAtomicState } from './doYouKnowAtomicState';

export function DoYoyKnowAtomicStateDisclamer() {
    // useStateAtom is like a shared version of useState
    const [answer, setAnswer] = useStateAtom(doYouKnowAtomicState);

    if (answer) {
        return null;
    }

    return (
        <div>
            Hey! Do you know AtomicState?
            <button onClick={() => setAnswer('yes')}>Yes!</button>
            <button onClick={() => setAnswer('no')}>No!</button>
        </div>
    );
}

./DoYoyKnowAtomicStateLinks.js

import { useStateAtom } from '@immobiliarelabs/atomic-state';
import { doYouKnowAtomicState } from './doYouKnowAtomicState';

export function DoYoyKnowAtomicStateLinks() {
    const [answer] = useStateAtom(doYouKnowAtomicState);

    if (answer === 'no') {
        return (
            <div>
                Oh really!?! Take a look{' '}
                <a href="https://github.com/immobiliare/atomic-state">here</a>,
                it's easy to pick up!
            </div>
        );
    }

    return null;
}

That's it and if you want to know more read the below docs!

Setup

To install the latest stable version, run the following command:

npm install @immobiliarelabs/atomic-state

Or if you're using yarn:

yarn add @immobiliarelabs/atomic-state

What is an atom?

An atom represents a piece of state. Atoms can be read from and written to from any component. Components that read the value of an atom are implicitly subscribed to that atom, so any atom updates will result in a re-render of all components subscribed to that atom:

import { createStateAtom, useStateAtom } from '@immobiliarelabs/atomic-state';

const yourNameAtom = createStateAtom({
    key: `YourName`, // unique ID
    default: '', // default value (aka initial value)
});

function TextInput() {
    // useStateAtom has the same behavior of useState
    const [yourName, setYourName] = useStateAtom(yourNameAtom);

    function handleChange(event) {
        setYourName(event.target.value);
    }

    return (
        <div>
            <label htmlFor="your-name">Your name:</label>
            <input
                id="your-name"
                type="text"
                onChange={handleChange}
                value={text}
            />
        </div>
    );
}

Deriving state

Derived atoms can be used to derive information from other atoms. They cache their output and triggers an update only when their output changes.

Conceptually, they are very similar to formulas in spreadsheets, and can't be underestimated. They help in reducing the amount of state you have to store and are highly optimized. Use them wherever possible.

import { createDerivedAtom, useAtomValue } from '@immobiliarelabs/atomic-state';
import { yourNameAtom } from './TextInput';

const yourNameIsFilledAtom = createDerivedAtom({
    key: `YourName/Filled`, // unique ID
    get(use) {
        return use(yourNameAtom) !== '';
    },
});

function TextInputFilledStatus() {
    // useAtomValue reads the state from an atom
    const filled = useAtomValue(yourNameIsFilledAtom);

    return <span>{filled ? 'Filled' : 'Empty'}</span>;
}

Effects

Atom effects are works in a similar way of React useEffect.

They have the same cleanup api and are executed only on the client side.

import { createStateAtom, useStateAtom } from '@immobiliarelabs/atomic-state';

const persistentModeAtom = createStateAtom({
    key: `PersistentMode`,
    default: true,
});

const textAtom = createStateAtom({
    key: `Text`,
    default: null,
    setup(self, { effect, get, set }) {
        /**
            `effect` lets you run effects after the atom update

            Like React.useEffect the effects are executed only in the browser after the paint
        */
        effect(
            (open) => {
                if (get(persistentModeAtom) !== true) return;

                if (get(self) === null) {
                    set(self, localStorage.getItem('LastEditedText') || '');
                } else {
                    localStorage.setItem('LastEditedText', get(self));
                }
            },
            [self]
        );
    },
});

Under the hood the atom effects are managed through React useEffect, so even in your unit tests they will behave exactly like useEffect.

Server Side Rendering

The first thing you have to do is place the AtomicStateProvider on top of your applications.

It is possible to hydrate the atoms state by passing a state object to it.

import {
    createStateAtom,
    AtomicStateProvider,
} from '@immobiliarelabs/atomic-state';
import { myFormAtom } from './atoms';

function MyApp({ formInitialState }) {
    /**
     * Every update of this value will trigger a `setState` on the related atoms
     *
     * This makes easy to update the atom values on page navigations
     */
    const atomsState = useMemo(
        () => ({
            [myFormAtom.key]: formInitialState,
        }),
        [formInitialState]
    );

    return (
        <AtomicStateProvider state={atomsState}>
            <AppCore />
        </AtomicStateProvider>
    );
}

DevTools

We have a devtools extension for Chrome

For more info take a look into the devtools docs

Powered Apps

AtomicState was created by the amazing frontend team at ImmobiliareLabs, the Tech dept at Immobiliare.it, the first real estate site in Italy.
We are currently using AtomicState in our products.

If you are using AtomicState in production drop us a message.

Support & Contribute

Made with ❀️ by ImmobiliareLabs & Contributors

We'd love for you to contribute to AtomicState! If you have any questions on how to use AtomicState, bugs and enhancement please feel free to reach out by opening a GitHub Issue.

License

AtomicState is licensed under the MIT license.
See the LICENSE file for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].