Skip to content

Repository files navigation

React Localux 🐛 — context-based store for React, TypeScript-friendly

npm version

React Localux (RL) is comfortable solution for separation store-related logic from react components. Unlike Redux main goal for RL is being home for compact local stores of smart components.

For example, you might have screen-like component of some item with vast logic related to this screen and it is required to support several different stacked screens of such items. Implementing such feature with global Redux store result complicated code, but it turns out that using single local store for each screen produces quite straightforward solution.

Example code (from example.tsx)

// item-store.tsimport{RLThunk,createStore}from'react-localux';// Utilstype$PartialMap<Textendsobject>={[PinkeyofT] ?: T[P]};constpause=async(timeout: number): Promise<any>=>newPromise(resolve=>setTimeout(resolve,timeout));typeState={loading: boolean,data?: string,error?: boolean,};constinitialState: State={loading: false,};constactions={loadItem: (): RLThunk<State,Promise<void>>=>async(getState,setState)=>{// You might need state in actionconststate=getState();setState(actions.loading());// Pretend making API call which can failawaitpause(1000);if(Math.random()>0.5){setState(actions.loadSucess('Hooray!😁'));}else{setState(actions.loadFailed());}},loading: (): $PartialMap<State>=>({loading: true,error: false,}),loadSucess: (data: string): $PartialMap<State>=>({loading: false,
data,}),loadFailed: (): $PartialMap<State>=>({loading: false,error: true,})};constcreateItemStore=()=>{returncreateStore(initialState,actions,);}typeItemStore=ReturnType<typeofcreateItemStore>;// item-screen.tsximportReactfrom'react';exportclassItemScreenextendsReact.Component{store: ItemStore;constructor(props: any){super(props);this.store=createItemStore();}publiccomponentDidMount(){const{ actions }=this.store;actions.loadItem();}publicrender(){const{
Provider
}=this.store;return(<Provider>{store=>(<div><h1>Item Screen</h1>{store.loading&&<p>Loading...</p>}{store.error&&<p>Error loading 😕</p>}{store.data&&<p>Data loaded 🎆: {store.data}</p>}</div>)}</Provider>);}// Alternative use of ProviderpublicalternativeRender(){const{
Provider,
Consumer
}=this.store;return(<Provider><Consumer>{store=>("...")}</Consumer></Provider>);}}

Comparing with similar solutions

react-waterfall:

  • No TypeScript support and due to API design decision for actions it is not possible to make types
  • No async actions support
  • Not very performant code on store creation

Alveron:

  • No TypeScript support

Actually I didn't find any similar library with TypeScript support 😕.

That's why this library has been born. 👭

Credits

Thanks to @viventus for helpfull discussions.

About

React Context API based store

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages