-
Notifications
You must be signed in to change notification settings - Fork 61
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
Don't work with react 18.2 #109
Comments
That's the intended behavior by design. |
I have more than 1000 components with useContextSeletor. Any changes in context value trigger call render function of all components. Even if it doesn't cause effects and update the DOM(only call render function), it takes a lot of computing resources. I change example and add Redux example: https://codesandbox.io/s/muddy-bush-ndqqwg?file=/src/App.js
100 components:
|
one more example - symetric updates states + calc render time, 1000 nodes: https://codesandbox.io/s/muddy-bush-ndqqwg?file=/src/App.js stats:
|
One workaround is to Another would be to use subscription based state management such as Redux / Zustand / ... You can also implement a simplified useContextSelector without concurrency support pretty easily. Seel also #100 |
import {
createContext as createContextOrig,
useContext as useContextOrig,
useRef,
useSyncExternalStore,
} from 'react';
export const createContext = (defaultValue) => {
const context = createContextOrig();
const ProviderOrig = context.Provider;
context.Provider = ({ value, children }) => {
const storeRef = useRef();
let store = storeRef.current;
if (!store) {
const listeners = new Set();
store = {
value,
subscribe: (l) => { listeners.add(l); return () => listeners.delete(l); },
notify: () => listeners.forEach((l) => l()),
}
storeRef.current = store;
}
useEffect(() => {
if (!Object.is(store.value, value)) {
store.value = value;
store.notify();
}
});
return <ProviderOrig value={store}>{children}</ProviderOrig>
};
return context;
}
export const useContextSelector = (context, selector) => {
const store = useContextOrig(context);
return useSyncExternalStore(
store.subscribe,
() => selector(store.value),
);
}; |
This works in React 18.2 and even works with |
Great to hear that, because I haven't tried it. 😁 |
However, |
I tried to add a cache with export function useContextSelector<T, Selected>(
context: React.Context<ContextStore<T>>,
selector: (value: T) => Selected,
) {
const store = useContext(context);
let cache: any;
return useSyncExternalStore(store.subscribe, () => {
const value = selector(store.value);
if (!shallowEqual(cache, value)) {
cache = value;
}
return cache;
});
} |
Use https://www.npmjs.com/package/use-sync-external-store instead and pass |
Components used useContextSelector with return save value always rerenders.
Example https://codesandbox.io/s/musing-poincare-hz2g6g?file=/src/App.js
The text was updated successfully, but these errors were encountered: