@air/react-memoized-context

中文文档
1.0.2发布于 2025/03/04MITTypeScriptESM + CJS近 30 天下载 2.8万
  • Use your React Context without the additional re-renders in the consumers - Ability to read values out of context "on-the-fly" - useful in callbacks so you don't have to bind the UI to a context value change just to use the value in a callback - Redux-l
原始使用文档
文档目录7 节
  1. ✨ Features
  2. About
  3. Why not React Context?
  4. Why not Redux?
  5. Install
  6. Usage
  7. Codesandbox

React Memoized Context

React Context with Redux-like performance and patterns without installing Redux.

size size

✨ Features

  • Use your React Context without the additional re-renders in the consumers
  • Ability to read values out of context "on-the-fly" - useful in callbacks so you don't have to bind the UI to a context value change just to use the value in a callback
  • Redux-like pattern (reducer, actions, and selectors)
  • Built with TypeScript

About

Here at Air, we needed a way to store multiple instances of complex global state (what React Context API does) but with the performance of Redux. react-memoized-context solves this problem.

Why not React Context?

A React Context provider renders all consumers every time it's value changes - even if the component isn't using a property on the value (if it's an object). This can cause lots of performance issues and the community is trying to solve it. We've looked at these other solutions but they're either not ready, have too many bugs or lacked features (like reading values on the fly) so we decided to roll our own.

Why not Redux?

Redux is great as a global store when multiple components want to read and write to a single centralized value. But when you want to have multiple global values with the same structure, Redux isn't as flexible because you need to duplicate your reducers, actions, and selectors. That's where React Context is nice because you can just wrap around another Provider.

Install

npm install --save @air/react-memoized-context
yarn add @air/react-memoized-context

Usage

  1. Create types for your context:

    • create type for value, which you want to store:
      export interface User {
        id: string;
        name: string;
        score: number;
      }
      
      export interface UsersTeamContextValue {
        users: User[];
      }
      
    • create type for actions you want to provide to update value:
      export interface UsersTeamContextActions {
        addUser: (user: User) => void;
        assignScore: (userId: User['id'], score: number) => void;
      }
      
    • create type for your context - remember to extend MemoizedContextType:
      export interface UsersTeamContextType extends MemoizedContextType<UsersTeamContextValue>, UsersTeamContextActionsType {}
      
    • create default value for your context:
      export const defaultUsersTeamContextValue: UsersTeamContextType = {
        ...defaultMemoizedContextValue,
        getValue: () => ({
          users: [],
        }),
        addUser: () => {},
        assignScore: () => {},
       };
      
    • create types for your actions - you will use them to modify context value:
      export interface AddUserAction extends MemoizedContextAction {
        type: 'addUser';
        data?: { user: User };
      }
        
      export interface AssignScoreAction extends MemoizedContextAction {
        type: 'assignScore';
        data?: { userId: User['id']; score: number };
      }
        
      export type UserTeamContextActions = AddUserAction | AssignScoreAction;
      
  2. Create your context:

    const UsersTeamContext = createContext<UsersTeamContextType>(defaultUsersTeamContextValue);
    
    const useUsersTeamContext = () => useContext(UsersTeamContext);
    
  3. Create your dispatch method. It should work as redux dispatch - takes an action, modifies state value and returns a new state:

    export const usersTeamContextDispatch = (state: UsersTeamContextValue, action: UserTeamContextActions) => {
      switch (action.type) {
        case 'assignScore':
          return {
            ...state,
            users: state.users.map((user) => {
              if (user.id === action.data?.userId) {
                return {
                  ...user,
                  score: action.data?.score ?? 0,
                };
              }
              return user;
            }),
          };
        case 'addUser':
          return {
            ...state,
            users: action.data ? [...state.users, action.data.user] : state.users,
          };
      }
    };
    
  4. Create your provider:

    export const UsersTeamProvider = ({ children }: PropsWithChildren<{}>) => {
      
      const { contextValue } = useMemoizedContextProvider<UsersTeamContextValue>(
        // provide default value for your context
        {
          users: [],
        },
        usersTeamContextDispatch,
      );
    
      // create methods you want to expose to clients
      const addUser = useCallback((user: User) => contextValue.dispatch({ type: 'addUser', data: { user } }), [contextValue]);
    
      const assignScore = useCallback(
        (userId: User['id'], score: number) => contextValue.dispatch({ type: 'assignScore', data: { userId, score } }),
        [contextValue],
      );
    
      // memoize your final value that will be available for clients
      // just return what's in contextValue and add your methods
      const value = useMemo<UsersTeamContextType>(
        () => ({
          ...contextValue,
          addUser,
          assignScore,
        }),
        [addUser, assignScore, contextValue],
      );
    
      return <UsersTeamContext.Provider value={value}>{children}</UsersTeamContext.Provider>;
    };
    
  5. To retrieve data from context, you need selectors:

    export const usersTeamUsersSelector = (state: UsersTeamContextValue) => state.users;
    

    usage in component:

    const context = useUsersTeamContext();
    // pass context to useMemoizedContextSelector
    const users = useMemoizedContextSelector(context, usersTeamUsersSelector);
    

    to simplify it, you can create a helper:

    export function useUsersTeamContextSelector<T>(selector: (st: UsersTeamContextValue) => T) {
      const context = useUsersTeamContext();
      return useMemoizedContextSelector(context, selector);
    }
    
    

    then, to retrieve users from context you can do:

    const users = useUsersTeamContextSelector(usersTeamUsersSelector);
    
  6. Start using your context!

    Wrap your components with your Provider component, as you do with React Context:

    <UsersTeamProvider>
        <UsersTeam name="Team 1" />
    </UsersTeamProvider>
    
To modify context value, use any of your actions:

```typescript
import { useUsersTeamContextSelector } from "./usersTeamContext";

const { addUser } = useUsersTeamContext()

const onClick = () => {
  addUser({ name: 'John' })
}

```

You can read context values on the fly if you need. For example, we will create a user with `users.length` as id. We can use `usersTeamUsersSelector`, but the component would be rerendered every time when any user changes. We don't want that - we need just `users` length. We could create a selector that gets users length, but again - everytime we add a user, the component will rerender. For us, it's enough to know users length by the time we create a user:
```typescript
 // get whole context value - it will not cause any rerender!
 const contextValue = useUsersTeamContext();

  const addNewUser = () => {
    // read users array when we need it
    const users = contextValue.getValue().users;
    // call addUser action to add a new user
    contextValue.addUser({ id: users.length + 1, name: userName, score: 0 });
  };
```

Codesandbox

You can play with the example using codesandbox: https://codesandbox.io/s/boring-morning-j44i9p

版本与发布记录

@air/react-memoized-context 共发布 3 个版本,首次发布于 2022/08/09;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.2latest2025/03/041.7 年前
1.0.12025/03/011.7 年前
1.0.02022/08/094 年前

关于 @air/react-memoized-context 的常见问题

@air/react-memoized-context 是什么?

Use your React Context without the additional re-renders in the consumers - Ability to read values out of context "on-the-fly" - useful in callbacks so you don't have to bind the UI to a context value change just to use the value in a callback - Redux-l

如何安装 @air/react-memoized-context?

在项目目录运行 npm install @air/react-memoized-context,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=17)、react-dom(>=17)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@air/react-memoized-context 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@air/react-memoized-context 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@air/react-memoized-context 可以商用吗?

@air/react-memoized-context 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@air/react-memoized-context 的下载量有多少?

根据 npm 官方下载统计,@air/react-memoized-context 在 2026/10/05 – 2026/11/03 这 30 天内被下载 28,236 次,日均约 941 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@air/react-memoized-context 还在维护吗?

最新版本 1.0.2 发布于 2025/03/04(1.7 年前);至今共发布 3 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/08/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。