All Projects → philipp-spiess → Use Substate

philipp-spiess / Use Substate

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

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Use Substate

Redhooks
Predictable state container for React apps written using Hooks
Stars: ✭ 149 (+53.61%)
Mutual labels:  hooks, state-management, reducer
Reto
Flexible and efficient React Store with hooks.
Stars: ✭ 194 (+100%)
Mutual labels:  hooks, state-management, store
RxReduxK
Micro-framework for Redux implemented in Kotlin
Stars: ✭ 65 (-32.99%)
Mutual labels:  state-management, store, reducer
Redux Orm
A small, simple and immutable ORM to manage relational data in your Redux store.
Stars: ✭ 2,922 (+2912.37%)
Mutual labels:  state-management, reducer
react-stateful-component
Functional stateful React components with sideEffect support
Stars: ✭ 19 (-80.41%)
Mutual labels:  state-management, reducer
React Recomponent
🥫 Reason-style reducer components for React using ES6 classes.
Stars: ✭ 272 (+180.41%)
Mutual labels:  state-management, reducer
micro-observables
A simple Observable library that can be used for easy state management in React applications.
Stars: ✭ 78 (-19.59%)
Mutual labels:  hooks, state-management
Redux Machine
A tiny library (12 lines) for creating state machines in Redux apps
Stars: ✭ 338 (+248.45%)
Mutual labels:  state-management, reducer
Akita
🚀 State Management Tailored-Made for JS Applications
Stars: ✭ 3,338 (+3341.24%)
Mutual labels:  state-management, store
Westore
更好的小程序项目架构
Stars: ✭ 3,897 (+3917.53%)
Mutual labels:  state-management, store
Redux Ecosystem Links
A categorized list of Redux-related addons, libraries, and utilities
Stars: ✭ 5,076 (+5132.99%)
Mutual labels:  store, reducer
Freezer
A tree data structure that emits events on updates, even if the modification is triggered by one of the leaves, making it easier to think in a reactive way.
Stars: ✭ 1,268 (+1207.22%)
Mutual labels:  state-management, store
atomic-state
A decentralized state management library for React
Stars: ✭ 54 (-44.33%)
Mutual labels:  hooks, state-management
Radioactive State
☢ Make Your React App Truly Reactive!
Stars: ✭ 273 (+181.44%)
Mutual labels:  hooks, state-management
zoov
Use 🐻 Zustand with Module-like api
Stars: ✭ 24 (-75.26%)
Mutual labels:  hooks, state-management
Constate
React Context + State
Stars: ✭ 3,519 (+3527.84%)
Mutual labels:  hooks, state-management
React Hooks
Essential set of React Hooks for convenient Web API consumption and state management.
Stars: ✭ 515 (+430.93%)
Mutual labels:  hooks, state-management
Reatom
State manager with a focus of all needs
Stars: ✭ 567 (+484.54%)
Mutual labels:  state-management, store
Use Global Context
A new way to use “useContext” better
Stars: ✭ 34 (-64.95%)
Mutual labels:  hooks, state-management
useStateMachine
The <1 kb state machine hook for React
Stars: ✭ 2,231 (+2200%)
Mutual labels:  hooks, state-management

🍙 useSubstate

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

function Component() {
  const [substate, dispatch] = useSubstate(state => {
    return { count: state.count };
  });

  return (
    <div>
      {substate.count}

      <button
        onClick={() => 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 React Unsafe)
  • 🎈 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 use useSubstate, you will need the unstable and experimental React 16.7.0-alpha. Check out the official documentation or this blog post by Dan Abramov for more information.

useSubstate can also be used together with react-redux in your existing Redux application. Check out Comparison To Redux for more information.

Installation

npm install --save use-substate

Usage

You can use useSubstate with your existing Redux store or with a simple alternative (like create-store). This package will export a React Context consumer (SubstateContext) as well the useSubstate hook.

This custom hook will expose an API similar to useReducer. The only argument for useSubstate is a selectSubstate function which is used to select parts of your state to be used within the component that uses the hook. This allows useSubstate 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 use useSubstate:

import React, { useState } from "react";
import ReactDOM from "react-dom";

import createStore from "create-store";
import { SubstateProvider, useSubstate } from "use-substate";

const initialState = { count: 0 };
function reducer(state, action) {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    case "DECREMENT":
      return { count: state.count - 1 };
  }
}
const store = createStore(reducer, initialState);

function App() {
  const [substate, dispatch] = useSubstate(state => {
    return { count: state.count };
  });

  return (
    <div>
      {substate.count}

      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
    </div>
  );
}

ReactDOM.render(
  <SubstateProvider value={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 to react-redux, this library only requires a selectSubstate function (similar to react-redux's mapStateToProps). It is meant to call the dispatch function with the action directly. Advanced concepts like connectAdvanced or mapDispatchToProps are deliberately not supported.

To use useSubstate with your current react-redux React application, find the react-redux Provider and make sure to wrap it with a SubstateProvider:

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 the open issue in react-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 of useReducer, 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 this repository, so you can work on your own environment.

  2. Install development dependencies locally:

    git clone [email protected]:<your-github-name>/use-substate.git
    cd use-substate
    yarn 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 the Pull 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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].