All Projects → mizchi → use-react-redux-context

mizchi / use-react-redux-context

Licence: other
Alternative ReactRedux.connect by useContext for performance

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to use-react-redux-context

React Cloud Music
React 16.8打造精美音乐WebApp
Stars: ✭ 1,722 (+3813.64%)
Mutual labels:  react-redux, react-hooks
rapid-react
A light weight interactive CLI Automation Tool 🛠️ for rapid scaffolding of tailored React apps with Create React App under the hood.
Stars: ✭ 73 (+65.91%)
Mutual labels:  react-redux, react-hooks
fetchye
✨ If you know how to use Fetch, you know how to use Fetchye [fetch-yae]. Simple React Hooks, Centralized Cache, Infinitely Extensible.
Stars: ✭ 36 (-18.18%)
Mutual labels:  react-redux, react-hooks
MetFlix
A Movie app demo. Like NetFlix ❤️
Stars: ✭ 50 (+13.64%)
Mutual labels:  react-redux, react-hooks
laravel-react-boilerplate
Laravel React Boilerplate with Ant Design, Route-Level Code Splitting, Redux, Sanctum Auth
Stars: ✭ 49 (+11.36%)
Mutual labels:  react-redux, react-hooks
awesome-web-react
🚀 Awesome Web Based React 🚀 Develop online with React!
Stars: ✭ 31 (-29.55%)
Mutual labels:  react-redux, react-hooks
promotion-web
基于React: v18.x.x/Webpack: v5.x.x/React Router v6.x.x/ Antd: v5..x.x/Fetch Api/ Typescript: v4.x.x 等最新版本进行构建...
Stars: ✭ 374 (+750%)
Mutual labels:  react-redux, react-hooks
React-Playground
Learning reactjs from the ground up (router, redux, thunk, hooks, context, portals, and functional components)
Stars: ✭ 15 (-65.91%)
Mutual labels:  react-redux, react-hooks
think
Instagram clone using React Native with funcional components, React Hooks, React Navigation 4x and Reactotron debugger
Stars: ✭ 20 (-54.55%)
Mutual labels:  react-redux, react-hooks
react-laravel
A simple crud based laravel app to learn how to use react with laravel.
Stars: ✭ 43 (-2.27%)
Mutual labels:  react-redux, react-hooks
react-antd-admin
基于vite2.x + react17.x + typescript4.x + antd4.x + react-router6.x + mobx6.x编写的一款简单高效的前后端分离的权限管理系统
Stars: ✭ 140 (+218.18%)
Mutual labels:  react-redux, react-hooks
react-guidebook
📚 React 知识图谱 关于概念、技巧、生态、前沿、源码核心
Stars: ✭ 22 (-50%)
Mutual labels:  react-redux, react-hooks
book-fullstack-react
Fullstack React: The Complete Guide to ReactJS and Friends by Anthony Accomazzo
Stars: ✭ 100 (+127.27%)
Mutual labels:  react-redux, react-hooks
boss
React+express+sock.io+mongodb build a boss
Stars: ✭ 25 (-43.18%)
Mutual labels:  react-redux
react-native-boilerplate
Expo + Redux + React Navigation Pre-setup Template (expo SDK 44)
Stars: ✭ 142 (+222.73%)
Mutual labels:  react-redux
furl
Functional react.js components.
Stars: ✭ 33 (-25%)
Mutual labels:  react-hooks
use-breakpoint
React `useBreakpoint` hook to have different values for a variable based on a breakpoints.
Stars: ✭ 17 (-61.36%)
Mutual labels:  react-hooks
stated-bean
A light but scalable view-model library with react hooks
Stars: ✭ 36 (-18.18%)
Mutual labels:  react-hooks
react-hook-layout
Layouts in React.
Stars: ✭ 16 (-63.64%)
Mutual labels:  react-hooks
energy-use-case-trading-client
Energy Use Case Web UI for Lition Trading Platform
Stars: ✭ 23 (-47.73%)
Mutual labels:  react-redux

use-react-redux-context

Alternative ReactRedux.connect() by useContext() for performance.

# peer deps
$ yarn add react react-dom redux react-redux
$ yarn add use-react-redux-context
# or npm install --save use-react-redux-context
yarn add @types/react @types/redux @types/react-redux -D # for typescript

Concept

  • Pre-defined connected React.Context with mapState (no own props)
  • Create bound actions by useCallback
  • Emit render by shallow equal comparation
  • TypeScript friendly

Why not useContext(ReactReduxContext) of react-redux@6

Just React.useContext(ReactReduxContext) emits rendering by all state update. Pre-defined contexts and reducers are good for performance.

And I don't know good ownProps usages on ReactRedux.connect.

How to use

Minimum conceptual code

import { Provider as ContextProvider, Scope } from "use-react-redux-context";
import { Provider as ReactReduxProvider } from "react-redux";

const scope = new Scope();
const RootStateContext = scope.createContext(s => s);
const All = () => {
  const all = useContext(RootStateContext);
  return <pre>{JSON.stringify(all)}</pre>;
};

const store = createStore(reducer); // create your reducer
const el = (
  <ReactReduxProvider store={store}>
    <ContextProvider scope={scope}>
      <All />
    </ContextProvider>
  </ReactReduxProvider>
);

Working code

import React, { useContext, useCallback, useEffect } from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers, Reducer } from "redux";
import { Provider as ReactReduxProvider } from "react-redux";
import { Provider as ContextProvider, Scope } from "use-react-redux-context";

// Write your own reducer

type Foo = {
  value: number;
};

type RootState = {
  foo: Foo;
};

type IncrementAction = { type: "increment" };
type Action = IncrementAction;

function foo(state: Foo = { value: 0 }, action: Action): Foo {
  switch (action.type) {
    case "increment": {
      return { value: state.value + 1 };
    }
    default: {
      return state;
    }
  }
}

function increment(): IncrementAction {
  return { type: "increment" };
}

// Build connected React.Context

const scope = new Scope<RootState>(); // scope expand all contexts
const FooContext = scope.createContext((state, dispatch) => {
  // this useCallback is under NewContext rendering hook context
  const inc = useCallback(() => dispatch(increment()), []);
  // emit render by shallow equal comparation
  return { ...state.foo, inc };
});

function Counter() {
  // This is React.useContext, not library function
  const foo = useContext(FooContext);
  return (
    <div>
      value: {foo.value}
      <button onClick={foo.inc}>+1</button>
    </div>
  );
}

const rootReducer: Reducer<RootState> = combineReducers({ foo });
const store = createStore(rootReducer);

function App() {
  return (
    // Provider expand all scope's context
    <ReactReduxProvider store={store}>
      <ContextProvider scope={scope}>
        <Counter />
      </ContextProvider>
    </ReactReduxProvider>
  );
}

// @ts-ignore
ReactDOM.render(<App />, document.querySelector(".root") as HTMLDivElement);

API

useDispatch

Get store.dispatch Function

import { useDispatch } from "use-react-redux-context";
function X() {
  const dispatch = useDispatch();
  return (
    <button onClick={() => disptach({ type: "my-action" })}>my action</button>
  );
}

useBindAction, useBindActions

Create function by action and actionMap (with useCallback and its memoizedKeys)

import { useBindAction, useBindActions } from "use-react-redux-context";

const A = scope.createContext(state => {
  const inc = useBindAction(increment);
  // with memoized keys
  // const inc = useBindAction(() => ({type: 'increment', payload: state.value}), [state.value]);
  return { ...state.a, inc };
});

const B = scope.createContext(_state => {
  const actions = useBindActions({ increment, decrement });
  // alternative: with memoized keys map
  // const actions = useBindActions({ increment, decrement }, { increment: [state.value] });

  // recommend spreading for shallow equal
  return { ...actions };
});

How to dev

  • yarn build: Build index.js
  • yarn test: Run jest
  • yarn demo: Start application server on http://localhost:1234
  • yarn demo:deploy: Deploy to netlify (need netlify account)

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].