Skip to content

[Question] - use-context-selector / Zustand / react-tracked - which is best for performance? #133

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

Closed
ItaiYosephi opened this issue Aug 14, 2024 · 3 comments

Comments

@ItaiYosephi
Copy link

My use case is a vary big UserPreference object that's provided globally, and a hook that accept a key and returns value, and setValue.
a simplified version of that looks like this (in reality user preferences comes from the server)

const useUserPreference = (key: keyof UserPreferences) => {
  const { userPreferences, setUserPreferences } = useContext(
    UserPreferencesContext
  );

  return {
    value: userPreferences[key],
    setValue: useCallback(
      nextValue =>
        setUserPreferences(prevUserPreferences => ({
          ...prevUserPreferences,
          [key]: nextValue,
        })),
      [key, setUserPreferences]
    ),
  };
};

const UserPreferencesProvider = ({ children }) => {
  const [userPreferences, setUserPreferences] = useState(INITIAL_VALUE);

  return (
    <UserPreferencesContext.Provider
      value={{ userPreferences, setUserPreferences }}
    >
      {children}
    </UserPreferencesContext.Provider>
  );
};

When setting value of a preference, I want to avoid rendering components that use useUserPreference if the value hasn't changed.
I tried using all three packages mentioned above, but rendering still occurs for every component that uses that hook...
any thoughts?

@dai-shi
Copy link
Owner

dai-shi commented Aug 14, 2024

All three packages should solve extra rerendering issue. You probably want to debug with useEffect(() => console.log('rendered')).

@ItaiYosephi
Copy link
Author

@dai-shi thanks! I was wondering what are the disadvantages of using the simple solution mentioned here #109 (comment) .
Does it support concurrency?

@dai-shi
Copy link
Owner

dai-shi commented Aug 16, 2024

I would actually recommend the simple solution.
Its drawback is when used with useTransition, but it still works.

use-context-selector is primarily developed for React Tracked and to pass my tests in https://github.com./dai-shi/will-this-react-global-state-work-in-concurrent-rendering.

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

2 participants