- Notifications
You must be signed in to change notification settings - Fork3
A decentralized state management library for React
License
immobiliare/atomic-state
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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 toshare state in asimple anddecentralized waywithout burdening your app size and complexity.
- 💡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.
- Quick start
- Setup
- What is an atom?
- Deriving state
- Effects
- Server Side Rendering
- DevTools
- Powered Apps
- Support & Contribute
- License
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 stateexportconstdoYouKnowAtomicState=createStateAtom({key:`DoYoyKnowAtomicState`,// unique IDdefault: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';exportfunctionDoYoyKnowAtomicStateDisclamer(){// useStateAtom is like a shared version of useStateconst[answer,setAnswer]=useStateAtom(doYouKnowAtomicState);if(answer){returnnull;}return(<div> Hey! Do you know AtomicState?<buttononClick={()=>setAnswer('yes')}>Yes!</button><buttononClick={()=>setAnswer('no')}>No!</button></div>);}
./DoYoyKnowAtomicStateLinks.js
import{useStateAtom}from'@immobiliarelabs/atomic-state';import{doYouKnowAtomicState}from'./doYouKnowAtomicState';exportfunctionDoYoyKnowAtomicStateLinks(){const[answer]=useStateAtom(doYouKnowAtomicState);if(answer==='no'){return(<div> Oh really!?! Take a look{' '}<ahref="https://github.com/immobiliare/atomic-state">here</a>, it's easy to pick up!</div>);}returnnull;}
That's it and if you want to know more read the below docs!
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
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';constyourNameAtom=createStateAtom({key:`YourName`,// unique IDdefault:'',// default value (aka initial value)});functionTextInput(){// useStateAtom has the same behavior of useStateconst[yourName,setYourName]=useStateAtom(yourNameAtom);functionhandleChange(event){setYourName(event.target.value);}return(<div><labelhtmlFor="your-name">Your name:</label><inputid="your-name"type="text"onChange={handleChange}value={text}/></div>);}
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';constyourNameIsFilledAtom=createDerivedAtom({key:`YourName/Filled`,// unique IDget(use){returnuse(yourNameAtom)!=='';},});functionTextInputFilledStatus(){// useAtomValue reads the state from an atomconstfilled=useAtomValue(yourNameIsFilledAtom);return<span>{filled ?'Filled' :'Empty'}</span>;}
Atom effects are works in a similar way of ReactuseEffect.
They have the samecleanup api and are executed only on the client side.
import{createStateAtom,useStateAtom}from'@immobiliarelabs/atomic-state';constpersistentModeAtom=createStateAtom({key:`PersistentMode`,default:true,});consttextAtom=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.
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';functionMyApp({ 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 */constatomsState=useMemo(()=>({[myFormAtom.key]:formInitialState,}),[formInitialState]);return(<AtomicStateProviderstate={atomsState}><AppCore/></AtomicStateProvider>);}
We have a devtools extension forChrome
For more info take a look into thedevtools docs
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 productiondrop us a message.
Made with ❤️ byImmobiliareLabs &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 aGitHub Issue.
AtomicState is licensed under the MIT license.
See theLICENSE file for more information.
About
A decentralized state management library for React