Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't work with react 18.2 #109

Closed
liknenS opened this issue Oct 27, 2023 · 10 comments
Closed

Don't work with react 18.2 #109

liknenS opened this issue Oct 27, 2023 · 10 comments

Comments

@liknenS
Copy link

liknenS commented Oct 27, 2023

Components used useContextSelector with return save value always rerenders.

Example https://codesandbox.io/s/musing-poincare-hz2g6g?file=/src/App.js

@dai-shi
Copy link
Owner

dai-shi commented Oct 27, 2023

That's the intended behavior by design.
Wrapping with useEffect should show more intuitive result:
https://codesandbox.io/s/interesting-mccarthy-m8vzyl?file=/src/App.js

@liknenS
Copy link
Author

liknenS commented Oct 30, 2023

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
With 10 components i has next stats:

aRender: 100
aEffect: 21
aChange: 2

bRender: 22
bEffect: 21
bChange: 2

100 components:

aRender: 800
aEffect: 201
aChange: 1

bRender: 202
bEffect: 201
bChange: 1

@liknenS
Copy link
Author

liknenS commented Oct 30, 2023

one more example - symetric updates states + calc render time, 1000 nodes: https://codesandbox.io/s/muddy-bush-ndqqwg?file=/src/App.js

stats:

change: 100

aRender: 206000
aEffect: 2200
aTime: 321.1000003814697

bRender: 2400
bEffect: 2200
bTime: 11.500000953674316

@dai-shi
Copy link
Owner

dai-shi commented Oct 30, 2023

Even if it doesn't cause effects and update the DOM(only call render function), it takes a lot of computing resources.

One workaround is to useMemo.

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

@dai-shi
Copy link
Owner

dai-shi commented Oct 30, 2023

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),
  );
};

@Jayatubi
Copy link

Jayatubi commented Nov 24, 2023

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

@dai-shi
Copy link
Owner

dai-shi commented Nov 24, 2023

Great to hear that, because I haven't tried it. 😁

@Jayatubi
Copy link

Jayatubi commented Nov 24, 2023

However, useContextSelector could only return a single result. I was tring to get multiple entries such as const { a, b } = useContextSelector(context, (root)=>({a: root.a, b: root.b})) but it cause useSyncExternalStore enter an infinity loop.

@Jayatubi
Copy link

Jayatubi commented Nov 24, 2023

I tried to add a cache with shallowEqual, from redux, to workaround but I'm not sure if that is ok. I'm not familiar to React.

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;
  });
}

@dai-shi
Copy link
Owner

dai-shi commented Nov 24, 2023

Use https://www.npmjs.com/package/use-sync-external-store instead and pass shallowEqual.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants