Installations
npm install @dbeining/react-atom
Developer
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
10.24.1
NPM Version
6.14.6
Statistics
158 Stars
135 Commits
7 Forks
4 Watching
28 Branches
1 Contributors
Updated on 14 Sept 2023
Bundle Size
6.42 kB
Minified
2.33 kB
Minified + Gzipped
Languages
TypeScript (88.44%)
JavaScript (10.67%)
Shell (0.89%)
Total Downloads
Cumulative downloads
Total Downloads
508,356
Last day
18.4%
869
Compared to previous day
Last week
-4.3%
3,193
Compared to previous week
Last month
47.5%
13,735
Compared to previous month
Last year
-13.4%
109,702
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Dev Dependencies
42
A simple way to manage shared state in React
Built on the React Hooks API
Inspired by atoms in reagent.cljs
- Description
- Why use
react-atom
? - Installation
- Documentation
- Code Example:
react-atom
in action - 🕹️ Play with
react-atom
in CodeSandbox 🎮️ - Contributing / Feedback
Description
react-atom
provides a very simple way to manage state in React, for both global app state and for local component state: ✨Atom
s✨.
Put your state in an Atom
:
1import { Atom } from "@dbeining/react-atom"; 2 3const appState = Atom.of({ 4 color: "blue", 5 userId: 1 6});
Read state with deref
You can't inspect Atom
state directly, you have to deref
erence it, like this:
1import { deref } from "@dbeining/react-atom"; 2 3const { 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:
1function 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
:
- it must return a value of the same type/interface as the previous state
- it must not mutate the previous state
To illustrate, here is how we might update appState
's color:
1import { swap } from "@dbeining/react-atom"; 2 3const setColor = color => 4 swap(appState, state => ({ 5 ...state, 6 color: color 7 }));
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:
1const saveColor = async color => { 2 const { userId } = deref(appState); 3 const theme = await post(`/api/user/${userId}/theme`, { color }); 4 swap(appState, state => ({ ...state, color: theme.color })); 5};
Re-render components on state change with the ✨useAtom
✨ custom React hook
useAtom
is a custom React Hook. It does two things:
- returns the current state of an atom (like
deref
), and - subscribes your component to the atom so that it re-renders every time its state changes
It looks like this:
1export function ColorReporter(props) { 2 const { color, userId } = useAtom(appState); 3 4 return ( 5 <div> 6 <p> 7 User {userId} has selected {color} 8 </p> 9 {/* `useAtom` hook will trigger a re-render on `swap` */} 10 <button onClick={() => swap(appState, setRandomColor)}>Change Color</button> 11 </div> 12 ); 13}
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
TheuseAtom
hook accepts an optionalselect
function that lets components subscribe to computed state. That means the component will only re-render when the value returned fromselect
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 thesetState
function in another function. That makes it hard to take advantage ofReact.memo
. For example:---1function Awkwardddd(props) { 2 const [name, setName] = useState(""); 3 const [bigState, setBigState] = useState({ ...useYourImagination }); 4 5 const updateName = evt => setName(evt.target.value); 6 const handleDidComplete = val => setBigState({ ...bigState, inner: val }); 7 8 return ( 9 <> 10 <input type="text" value={name} onChange={updateName} /> 11 <ExpensiveButMemoized data={bigState} onComplete={handleDidComplete} /> 12 </> 13 ); 14}
Every time
input
firesonChange
,ExpensiveButMemoized
has to re-render becausehandleDidComplete
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.1const state = Atom.of({ name, bigState: { ...useYourImagination } }); 2 3const updateName = ({ target }) => swap(state, prev => ({ ...prev, name: target.value })); 4 5const handleDidComplete = val => 6 swap(state, prev => ({ 7 ...prev, 8 bigState: { ...prev.bigState, inner: val } 9 })); 10 11function SoSmoooooth(props) { 12 const { name, bigState } = useAtom(state); 13 14 return ( 15 <> 16 <input type="text" value={name} onChange={updateName} /> 17 <ExpensiveButMemoized data={bigState} onComplete={handleDidComplete} /> 18 </> 19 ); 20}
TS First-class TypeScript support
react-atom
is written in TypeScript so that every release is published with correct, high quality typings.
⚛️ Embraces React's future with Hooks
Hooks will makeclass
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, react@^16.8.0
and react-dom@^16.8.0
, which contain the Hooks API.
Documentation
Code Example: react-atom
in action
Click for code sample
1import React from "react"; 2import ReactDOM from "react-dom"; 3import { Atom, useAtom, swap } from "@dbeining/react-atom"; 4 5//------------------------ APP STATE ------------------------------// 6 7const stateAtom = Atom.of({ 8 count: 0, 9 text: "", 10 data: { 11 // ...just imagine 12 } 13}); 14 15//------------------------ EFFECTS ------------------------------// 16 17const increment = () => 18 swap(stateAtom, state => ({ 19 ...state, 20 count: state.count + 1 21 })); 22 23const decrement = () => 24 swap(stateAtom, state => ({ 25 ...state, 26 count: state.count - 1 27 })); 28 29const updateText = evt => 30 swap(stateAtom, state => ({ 31 ...state, 32 text: evt.target.value 33 })); 34 35const loadSomething = () => 36 fetch("https://jsonplaceholder.typicode.com/todos/1") 37 .then(res => res.json()) 38 .then(data => swap(stateAtom, state => ({ ...state, data }))) 39 .catch(console.error); 40 41//------------------------ COMPONENT ------------------------------// 42 43export const App = () => { 44 const { count, data, text } = useAtom(stateAtom); 45 46 return ( 47 <div> 48 <p>Count: {count}</p> 49 <p>Text: {text}</p> 50 51 <button onClick={increment}>Moar</button> 52 <button onClick={decrement}>Less</button> 53 <button onClick={loadSomething}>Load Data</button> 54 <input type="text" onChange={updateText} value={text} /> 55 56 <p>{JSON.stringify(data, null, " ")}</p> 57 </div> 58 ); 59}; 60 61ReactDOM.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 |
---|---|
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).
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
project is archived
Details
- Warn: Repository is archived.
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Reason
77 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-v88g-cgmw-v5xw
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-fwr7-v2mv-hh25
- Warn: Project is vulnerable to: GHSA-cwfw-4gq5-mrqx
- Warn: Project is vulnerable to: GHSA-g95f-p29q-9xw4
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-x9w5-v3q2-3rhw
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-w573-4hg7-7wgq
- Warn: Project is vulnerable to: GHSA-ff7x-qrg7-qggm
- Warn: Project is vulnerable to: GHSA-434g-2637-qmqr
- Warn: Project is vulnerable to: GHSA-49q7-c7j4-3p7m
- Warn: Project is vulnerable to: GHSA-977x-g7h5-7qgw
- Warn: Project is vulnerable to: GHSA-f7q4-pwc6-w24p
- Warn: Project is vulnerable to: GHSA-fc9h-whq2-v747
- Warn: Project is vulnerable to: GHSA-8r6j-v8pm-fqw3
- Warn: Project is vulnerable to: MAL-2023-462
- Warn: Project is vulnerable to: GHSA-ww39-953v-wcq6
- Warn: Project is vulnerable to: GHSA-pfrx-2q88-qq97
- Warn: Project is vulnerable to: GHSA-7wwv-vh3v-89cq
- Warn: Project is vulnerable to: GHSA-rc47-6667-2j5j
- Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-896r-f27r-55mw
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-6c8f-qphg-qjgp
- Warn: Project is vulnerable to: GHSA-76p3-8jx3-jpfq
- Warn: Project is vulnerable to: GHSA-3rfm-jhwj-7488
- Warn: Project is vulnerable to: GHSA-hhq3-ff78-jv3g
- Warn: Project is vulnerable to: GHSA-jf85-cpcp-j695
- Warn: Project is vulnerable to: GHSA-p6mc-m468-83gw
- Warn: Project is vulnerable to: GHSA-29mw-wpgm-hmr9
- Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm
- Warn: Project is vulnerable to: GHSA-4xc9-xhrj-v574
- Warn: Project is vulnerable to: GHSA-x5rq-j2xg-h7qm
- Warn: Project is vulnerable to: GHSA-h726-x36v-rx45
- Warn: Project is vulnerable to: GHSA-779f-wgxg-qr8f
- Warn: Project is vulnerable to: GHSA-xf5p-87ch-gxw2
- Warn: Project is vulnerable to: GHSA-ch52-vgq2-943f
- Warn: Project is vulnerable to: GHSA-5v2h-r2cx-5xgj
- Warn: Project is vulnerable to: GHSA-rrrm-qjm4-v8hf
- Warn: Project is vulnerable to: GHSA-4xcv-9jjx-gfj3
- Warn: Project is vulnerable to: GHSA-7wpw-2hjm-89gp
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-vh95-rmgr-6w4m / GHSA-xvch-5gv4-984h
- Warn: Project is vulnerable to: GHSA-r683-j2x4-v87g
- Warn: Project is vulnerable to: GHSA-w7rc-rwvf-8q5r
- Warn: Project is vulnerable to: GHSA-5fw9-fq32-wv5p
- Warn: Project is vulnerable to: GHSA-hj48-42vr-x3v9
- Warn: Project is vulnerable to: GHSA-hrpp-h998-j3pp
- Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6
- Warn: Project is vulnerable to: GHSA-r2j6-p67h-q639
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-44c6-4v22-4mhx
- Warn: Project is vulnerable to: GHSA-4x5v-gmq8-25ch
- Warn: Project is vulnerable to: GHSA-h9rv-jmmf-4pgx
- Warn: Project is vulnerable to: GHSA-hxcc-f52p-wc94
- Warn: Project is vulnerable to: GHSA-4g88-fppr-53pp
- Warn: Project is vulnerable to: GHSA-4jqc-8m5r-9rpr
- Warn: Project is vulnerable to: GHSA-4rq4-32rv-6wp6
- Warn: Project is vulnerable to: GHSA-64g7-mvw6-v9qj
- Warn: Project is vulnerable to: GHSA-9r2w-394v-53qc
- Warn: Project is vulnerable to: GHSA-5955-9wpr-37jh
- Warn: Project is vulnerable to: GHSA-qq89-hq3f-393p
- Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
- Warn: Project is vulnerable to: GHSA-4wf5-vphf-c2xc
- Warn: Project is vulnerable to: GHSA-jgrx-mgxx-jf9v
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-7p7h-4mm5-852v
- Warn: Project is vulnerable to: GHSA-38fc-wpqx-33j7
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-6fc8-4gx4-v693
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
- Warn: Project is vulnerable to: GHSA-p9pc-299p-vxgp
Score
2
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More