Gathering detailed insights and metrics for @dbeining/react-atom
Gathering detailed insights and metrics for @dbeining/react-atom
Gathering detailed insights and metrics for @dbeining/react-atom
Gathering detailed insights and metrics for @dbeining/react-atom
npm install @dbeining/react-atom
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
158 Stars
135 Commits
7 Forks
4 Watching
28 Branches
1 Contributors
Updated on 14 Sept 2023
Minified
Minified + Gzipped
TypeScript (88.44%)
JavaScript (10.67%)
Shell (0.89%)
Cumulative downloads
Total Downloads
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
1
42
react-atom
?react-atom
in actionreact-atom
in CodeSandbox 🎮️react-atom
provides a very simple way to manage state in React, for both global app state and for local component state: ✨Atom
s✨.
Atom
:1import { Atom } from "@dbeining/react-atom"; 2 3const appState = Atom.of({ 4 color: "blue", 5 userId: 1 6});
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);
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
:
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
.
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};
useAtom
✨ custom React hookuseAtom
is a custom React Hook. It does two things:
deref
), andIt 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.
react-atom
?`Atom.of`, `useAtom`, and `swap` will cover the vast majority of use cases.
Reducers? Actions? Thunks? Sagas? Nope, just `swap(atom, state => newState)`.
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}
react-atom
is written in TypeScript so that every release is published with correct, high quality typings.
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.
npm i -S @dbeining/react-atom
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.
react-atom
in action1import 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"));
react-atom
in CodeSandbox 🎮️You can play with react-atom
live right away with no setup at the following links:
JavaScript Sandbox | TypeScript Sandbox |
---|---|
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
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
project is archived
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
77 existing vulnerabilities detected
Details
Score
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