🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more

use-perf-context

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-perf-context

高性能 useContext, 解决re-render问题

1.0.2
latest
Version published
Weekly downloads
3
Maintainers
1
Weekly downloads
 
Created

use-perf-context

titlecontent
系统名称use-perf-context
项目负责人mortimerliu(阿吉)
作者mortimerliu(阿吉)
文档提交日期2022.10.14


修订历史

版本号作者修订章节修订原因修订日期
1.0mortimerliuallfirst publish2022.10.14


1.About

This is a hight performance react component, which avoid re-render of Context Component.

This implements a more refined rendering strategy and you don't feel it.

Actually, two common ways to avoid re-render are multi-layered contexts and memo components.

Nut they make number of codes too much.I don't like those ways.

I want something easy to use, and the number of my codes is less.

Then use-perf-context was born.

2.Usage

// App.tsx
import PerfContextProvider from "use-perf-context";
function App() {
  // provide Context
  return (
    <PerfContextProvider state={initialState} reducer={globalReducer}>
      <Header />
      <YourComponents />
    </PerfContextProvider>
  );
}

// Header.tsx
import PerfContextProvider from "use-perf-context";
function Header() {
  // consume Context
  // usePerfContext<target property type constraint, dispatch's parame type constraint>
  const [userInfo, dispatch] = usePerfContext<IUserInfo, IAction>("userInfo");

  const { name, age } = userInfo || {};
  renderCount++;
  const addAge = () => {
    dispatch({
      type: ActionType.SET_USER_INFO,
      payload: { name: "mortimer", age: Number(age) + 1 },
    });
  };

  return (
    <div className={classPrefix}>
      <div>{classPrefix}</div>
      <div>user name is :{name}</div>
      <div>user age is :{age}</div>
      <button onClick={addAge}>add age +1</button>
      <div>renderCount: {renderCount}</div>
    </div>
  );
}

// Context Store
export interface IUserInfo {
  name: string;
  age: number;
}
export interface IAction {
  type: ActionType;
  payload?: any;
}
export enum ActionType {
  SET_USER_INFO = "SET_USER_INFO",
}
export const initialState: IState = {
  userInfo: {
    name: "",
    age: 0,
  },
};
export const reducer = (state: IState, action: IAction) => {
  switch (action.type) {
    case ActionType.SET_USER_INFO:
      return {
        ...state,
        userInfo: action.payload,
      };
    default:
      return state;
  }
};

3.example demo

CodeSandBox demo: https://codesandbox.io/s/void4-context-rerender--proxy-completed-emv5n0?file=/src/store/index.tsx

FAQs

Package last updated on 14 Oct 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts