react-tracked
- dai-shi/react-tracked
- createTrackedSelector - useSelector -> useTrackedSelector
- 访问属性会被 watch、select
- createContainer
- 提供类似 useReducer 的 hook
- 返回 Provider, useTracked, useUpdate, useTrackedState, useSelector,
- concurrentMode -> useContextUpdate use-context-selector
- memo - 会处理 proxy 对象值变化
- getUntrackedObject - 获取原始值
caution
- useTrackedState 每次返回新的 proxy 对象 - 不等
- React.memo 无法处理传入 proxy 对象,导致值变化但不 rerender
- 传值到 render 之外时记得 getUntrackedObject
const reducer = () => {};
const { Provider, useTracked } = createContainer(({ reducer, initialState, init }) =>
useReducer(reducer, initialState, init),
);
// 直接使用状态的方式
const {} = createContainer(({ initialState = {} }) => useState(initialState));
// 使用 immer 更新
import produce from 'immer';
const useTrackedWithImmer = () => {
const [state, setState] = useTracked();
const update = useCallback(
(updater) => {
setState((oldVal) => produce(oldVal, updater));
},
[setState],
);
return [state, update];
};
const App = ({ initialState }) => (
<Provider reducer={reducer} initialState={initialState}>
...
</Provider>
);