Skip to content

broken in react 18 #100

@dontsave

Description

@dontsave

hi there. I love use-context-selector but after recently upgrading a large codebase to react 18, we noticed that it stopped behaving as expected. subscribers to the context are rerendering, regardless of whether their selector returns a changed value or not. for example in this case:

import { memo, useState } from 'react';
import { createContext, useContextSelector } from 'use-context-selector';

export default {
  title: 'spike',
  component: null,
};

export const Demo = () => {
  const [state, setState] = useState({ count: 0, foo: false });
  return (
    <CTX.Provider value={state}>
      <div>
        <button onClick={() => setState((prev) => ({ ...prev, foo: true }))}>
          button
        </button>
        <div>
          {[...new Array(100)].map((_, i) => {
            return <Div key={i} id={i} />;
          })}
        </div>
      </div>
    </CTX.Provider>
  );
};

const CTX = createContext({ count: 0 });

const Div = memo(({ id }: any) => {
  const count = useContextSelector(CTX, (val) => val.count); // <-- always 0!!
  console.log(`!`); // <-- logs 100 times!

  return <div key={id}>{count}</div>;
});

clicking the button changes a part of the state that is not used by any of the consumers of the context. however they all still rerender anyway. this seems to defeat the purpose of the library, which is to prevent unnecessary rerenders. any guidance you have would be appreciated here

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions