npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dbeining/react-atom

v4.1.21

Published

State management made simple for React. Built on React Hooks. Inspired by `atom`s in `reagent.cljs`.

Downloads

13,186

Readme

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?

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} />
    </>
  );
}

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, react@^16.8.0 and react-dom@^16.8.0, which contain the Hooks API.

Documentation

react-atom API

@libre/atom API

Code Example: react-atom in action

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