All Projects → derrickbeining → React Atom

derrickbeining / React Atom

Licence: mit
A simple way manage state in React, inspired by Clojure(Script) and reagent.cljs

Programming Languages

typescript
32286 projects
clojurescript
191 projects
cljs
18 projects

Projects that are alternatives of or similar to React Atom

micro-observables
A simple Observable library that can be used for easy state management in React applications.
Stars: ✭ 78 (-41.35%)
Mutual labels:  hooks, state-management, mobx
hooksy
Simple app state management based on react hooks
Stars: ✭ 58 (-56.39%)
Mutual labels:  hooks, state-management, mobx
React Hooks
Essential set of React Hooks for convenient Web API consumption and state management.
Stars: ✭ 515 (+287.22%)
Mutual labels:  hooks, state-management
Pullstate
Simple state stores using immer and React hooks - re-use parts of your state by pulling it anywhere you like!
Stars: ✭ 683 (+413.53%)
Mutual labels:  hooks, state-management
React Context Hook
A React.js global state manager with Hooks
Stars: ✭ 50 (-62.41%)
Mutual labels:  hooks, state-management
Blue Chip
Normalizes GraphQL and JSON:API payloads into your state management system and provides ORM selectors to prepare data to be consumed by components
Stars: ✭ 332 (+149.62%)
Mutual labels:  state-management, mobx
Easy Peasy
Vegetarian friendly state for React
Stars: ✭ 4,525 (+3302.26%)
Mutual labels:  hooks, state-management
Use Global Context
A new way to use “useContext” better
Stars: ✭ 34 (-74.44%)
Mutual labels:  hooks, state-management
Radioactive State
☢ Make Your React App Truly Reactive!
Stars: ✭ 273 (+105.26%)
Mutual labels:  hooks, state-management
Reactstatemuseum
A whirlwind tour of React state management systems by example
Stars: ✭ 1,294 (+872.93%)
Mutual labels:  state-management, mobx
Compare React State Management
React createContext vs Apollo vs MobX vs Redux in a simple todo app.
Stars: ✭ 81 (-39.1%)
Mutual labels:  state-management, mobx
Use Substate
🍙 Lightweight (<600B minified + gzipped) React Hook to subscribe to a subset of your single app state.
Stars: ✭ 97 (-27.07%)
Mutual labels:  hooks, state-management
Constate
React Context + State
Stars: ✭ 3,519 (+2545.86%)
Mutual labels:  hooks, state-management
React Coat
Structured React + Redux with Typescript and support for isomorphic rendering beautifully(SSR)
Stars: ✭ 290 (+118.05%)
Mutual labels:  state-management, mobx
Mobx Router
A simple router for MobX + React apps
Stars: ✭ 489 (+267.67%)
Mutual labels:  hooks, mobx
Mobx Keystone
A MobX powered state management solution based on data trees with first class support for Typescript, support for snapshots, patches and much more
Stars: ✭ 284 (+113.53%)
Mutual labels:  state-management, mobx
Mobx State Tree
Full-featured reactive state management without the boilerplate
Stars: ✭ 6,317 (+4649.62%)
Mutual labels:  state-management, mobx
Datx
DatX is an opinionated JS/TS data store. It features support for simple property definition, references to other models and first-class TypeScript support.
Stars: ✭ 111 (-16.54%)
Mutual labels:  state-management, mobx
zoov
Use 🐻 Zustand with Module-like api
Stars: ✭ 24 (-81.95%)
Mutual labels:  hooks, state-management
atomic-state
A decentralized state management library for React
Stars: ✭ 54 (-59.4%)
Mutual labels:  hooks, state-management

react-atom logo

A simple way to manage shared state in React

Built on the React Hooks API

Inspired by atoms in reagent.cljs

TypeScript npm (scoped) npm bundle size (minified) npm bundle size (minified + gzip)

Build Status codecov npm

NpmLicense Commitizen friendly semantic-release

Description

react-atom provides a very simple way to manage state in React, for both global app state and for local component state: ✨Atoms✨.

Put your state in an Atom:

import { Atom } from "@dbeining/react-atom";

const appState = Atom.of({
  color: "blue",
  userId: 1
});

Read state with deref

You can't inspect Atom state directly, you have to dereference it, like this:

import { deref } from "@dbeining/react-atom";

const { color } = deref(appState);

Update state with swap

You can't modify an Atom directly. The main way to update state is with swap. Here's its call signature:

function swap<S>(atom: Atom<S>, updateFn: (state: S) => S): void;

updateFn is applied to atom's state and the return value is set as atom's new state. There are just two simple rules for updateFn:

  1. it must return a value of the same type/interface as the previous state
  2. it must not mutate the previous state

To illustrate, here is how we might update appState's color:

import { swap } from "@dbeining/react-atom";

const setColor = color =>
  swap(appState, state => ({
    ...state,
    color: color
  }));

Take notice that our updateFn is spreading the old state onto a new object before overriding color. This is an easy way to obey the rules of updateFn.

Side-Effects? Just use swap

You don't need to do anything special for managing side-effects. Just write your IO-related logic as per usual, and call swap when you've got what you need. For example:

const saveColor = async color => {
  const { userId } = deref(appState);
  const theme = await post(`/api/user/${userId}/theme`, { color });
  swap(appState, state => ({ ...state, color: theme.color }));
};

Re-render components on state change with the ✨useAtom✨ custom React hook

useAtom is a custom React Hook. It does two things:

  1. returns the current state of an atom (like deref), and
  2. subscribes your component to the atom so that it re-renders every time its state changes

It looks like this:

export function ColorReporter(props) {
  const { color, userId } = useAtom(appState);

  return (
    <div>
      <p>
        User {userId} has selected {color}
      </p>
      {/* `useAtom` hook will trigger a re-render on `swap` */}
      <button onClick={() => swap(appState, setRandomColor)}>Change Color</button>
    </div>
  );
}

Nota Bene: You can also use a selector to subscribe to computed state by using the options.select argument. Read the docs for details.

Why use react-atom?

😌 Tiny API / learning curve
`Atom.of`, `useAtom`, and `swap` will cover the vast majority of use cases.
🚫 No boilerplate, just predictable state management
Reducers? Actions? Thunks? Sagas? Nope, just `swap(atom, state => newState)`.
🎵 Tuned for performant component rendering
The useAtom hook accepts an optional select function that lets components subscribe to computed state. That means the component will only re-render when the value returned from select changes.
😬 React.useState doesn't play nice with React.memo
useState is cool until you realize that in most cases it forces you to pass new function instances through props on every render because you usually need to wrap the setState function in another function. That makes it hard to take advantage of React.memo. For example:
---
function Awkwardddd(props) {
  const [name, setName] = useState("");
  const [bigState, setBigState] = useState({ ...useYourImagination });

  const updateName = evt => setName(evt.target.value);
  const handleDidComplete = val => setBigState({ ...bigState, inner: val });

  return (
    <>
      <input type="text" value={name} onChange={updateName} />
      <ExpensiveButMemoized data={bigState} onComplete={handleDidComplete} />
    </>
  );
}

Every time input fires onChange, ExpensiveButMemoized has to re-render because handleDidComplete is not strictly equal (===) to the last instance passed down.

The React docs admit this is awkward and suggest using Context to work around it, because the alternative is super convoluted.

With react-atom, this problem doesn't even exist. You can define your update functions outside the component so they are referentially stable across renders.

const state = Atom.of({ name, bigState: { ...useYourImagination } });

const updateName = ({ target }) => swap(state, prev => ({ ...prev, name: target.value }));

const handleDidComplete = val =>
  swap(state, prev => ({
    ...prev,
    bigState: { ...prev.bigState, inner: val }
  }));

function SoSmoooooth(props) {
  const { name, bigState } = useAtom(state);

  return (
    <>
      <input type="text" value={name} onChange={updateName} />
      <ExpensiveButMemoized data={bigState} onComplete={handleDidComplete} />
    </>
  );
}
TS First-class TypeScript support
react-atom is written in TypeScript so that every release is published with correct, high quality typings.
👣 Tiny footprint
⚛️ Embraces React's future with Hooks
Hooks will make class components and their kind (higher-order components, render-prop components, and function-as-child components) obsolete. react-atom makes it easy to manage shared state with just function components and hooks.

Installation

npm i -S @dbeining/react-atom

Dependencies

react-atom has one bundled dependency, @libre/atom, which provides the Atom data type. It is re-exported in its entirety from @dbeining/atom. You may want to reference the docs here.

react-atom also has two peerDependencies, namely, [email protected]^16.8.0 and [email protected]^16.8.0, which contain the Hooks API.

Documentation

react-atom API

@libre/atom API

Code Example: react-atom in action

Click for code sample
import React from "react";
import ReactDOM from "react-dom";
import { Atom, useAtom, swap } from "@dbeining/react-atom";

//------------------------ APP STATE ------------------------------//

const stateAtom = Atom.of({
  count: 0,
  text: "",
  data: {
    // ...just imagine
  }
});

//------------------------ EFFECTS ------------------------------//

const increment = () =>
  swap(stateAtom, state => ({
    ...state,
    count: state.count + 1
  }));

const decrement = () =>
  swap(stateAtom, state => ({
    ...state,
    count: state.count - 1
  }));

const updateText = evt =>
  swap(stateAtom, state => ({
    ...state,
    text: evt.target.value
  }));

const loadSomething = () =>
  fetch("https://jsonplaceholder.typicode.com/todos/1")
    .then(res => res.json())
    .then(data => swap(stateAtom, state => ({ ...state, data })))
    .catch(console.error);

//------------------------ COMPONENT ------------------------------//

export const App = () => {
  const { count, data, text } = useAtom(stateAtom);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Text: {text}</p>

      <button onClick={increment}>Moar</button>
      <button onClick={decrement}>Less</button>
      <button onClick={loadSomething}>Load Data</button>
      <input type="text" onChange={updateText} value={text} />

      <p>{JSON.stringify(data, null, "  ")}</p>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

🕹️ Play with react-atom in CodeSandbox 🎮️

You can play with react-atom live right away with no setup at the following links:

JavaScript Sandbox TypeScript Sandbox
try react-atom try react-atom

Contributing / Feedback

Please open an issue if you have any questions, suggestions for improvements/features, or want to submit a PR for a bug-fix (please include tests if applicable).

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].