Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🍙 Lightweight (<600B minified + gzipped) React Hook to subscribe to a subset of your single app state.

License

NotificationsYou must be signed in to change notification settings

philipp-spiess/use-substate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Lightweight (<600B minified + gzipped) React Hook tosubscribe to asubset of your single app state.

functionComponent(){const[substate,dispatch]=useSubstate(state=>{return{count:state.count};});return(<div>{substate.count}<buttononClick={()=>dispatch({type:"INCREMENT"})}>        Increment</button></div>);}

Features

  • ⏬ Lightweight (<600B minified + gzipped)
  • ⚛️ Works with your existing Redux-like store
  • 🙅‍♀️ Avoids unnecessary re-renders
  • 🔂 Uses an external event subscription to short-circuit context propagation (Making it Concurrent ReactUnsafe)
  • 🎈 Full Flow and TypeScript support coming soon
  • 🎮 You’re in full control of your store and can use it outside React as well

Requirements

⚠️ To useuseSubstate, you will need the unstable and experimental React 16.7.0-alpha. Check out theofficial documentation orthis blog post by Dan Abramov for more information.

useSubstate can also be used together withreact-redux in your existingRedux application. Check outComparison To Redux for more information.

Installation

npm install --save use-substate

Usage

You can useuseSubstate with your existingRedux store or with a simple alternative (likecreate-store). This package will export aReact Context consumer (SubstateContext) as well theuseSubstate hook.

This custom hook will expose an API similar touseReducer. The only argument foruseSubstate is aselectSubstate function which is used to select parts of your state to be used within the component that uses the hook. This allowsuseSubstate to bail out if unnecessary parts change. Every component that uses this custom hook will automatically subscribe to the store.

The example below will show all steps necessary to useuseSubstate:

importReact,{useState}from"react";importReactDOMfrom"react-dom";importcreateStorefrom"create-store";import{SubstateProvider,useSubstate}from"use-substate";constinitialState={count:0};functionreducer(state,action){switch(action.type){case"INCREMENT":return{count:state.count+1};case"DECREMENT":return{count:state.count-1};}}conststore=createStore(reducer,initialState);functionApp(){const[substate,dispatch]=useSubstate(state=>{return{count:state.count};});return(<div>{substate.count}<buttononClick={()=>dispatch({type:"INCREMENT"})}>Increment</button><buttononClick={()=>dispatch({type:"DECREMENT"})}>Decrement</button></div>);}ReactDOM.render(<SubstateProvidervalue={store}><App/></SubstateProvider>,rootElement);

Edit useSubstate Example

Comparison To Redux

Redux is a library used to create stores that can be updated via reducers. In fact,useSubstate works flawlessly with your current Redux store.

In opposite toreact-redux, this library only requires aselectSubstate function (similar toreact-redux'smapStateToProps). It is meant to call thedispatch function with the action directly. Advanced concepts likeconnectAdvanced ormapDispatchToProps are deliberately not supported.

To useuseSubstate with your currentreact-redux React application, find the react-reduxProvider and make sure to wrap it with aSubstateProvider:

import React from "react";import { render } from "react-dom";import { Provider } from "react-redux";+ import { SubstateProvider } from "use-substate";import { createStore } from "redux";import todoApp from "./reducers";import App from "./components/App";const store = createStore(todoApp);render(+ <SubstateProvider value={store}>    <Provider store={store}>      <App />    </Provider>+ </SubstateProvider>,  document.getElementById("root"));

Other Libraries

Besides theopen issue inreact-redux, there are two other noticeable libraries that solve the a similiar problem:

Acknowledgements

Special thanks to@sophiebits and@gaearon for helping me spot an issue in my initial implementation and showing me how to fix it.

This library is also heavily influenced by the design ofuseReducer,create-subscription,react-redux,Reducer components in ReasonReact,Elm,Reagent (Clojure),Om (Clojure), and a lot of other libraries that I have seen over the years. Thank you all for pushing the Web forward ❤️.

Contributing

Every help on this project is greatly appreciated. To get you started, here's a quick guide on how to make good and clean pull-requests:

  1. Create a fork of thisrepository, so you can work on your own environment.

  2. Install development dependencies locally:

    git clone git@github.com:<your-github-name>/use-substate.gitcd use-substateyarn install
  3. Make changes using your favorite editor.

  4. Commit your changes (here is a wonderful guide on how to make amazing git commits).

  5. After a few seconds, a button to create a pull request should be visible inside thePull requests section.

Future Improvements

  • Add Flow and TypeScript types. This is actually very important for this library: Actions must be typed as an enum such that the type system can find out if we use the wrong type.
  • Improve test harness.

License

MIT

About

🍙 Lightweight (<600B minified + gzipped) React Hook to subscribe to a subset of your single app state.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp