ably-js icon indicating copy to clipboard operation
ably-js copied to clipboard

Move `React.createContext` outside of components

Open VeskeR opened this issue 11 months ago • 0 comments

Currently we call React.createContext during render in AblyProvider, so we can have arbitrary amount of contexts accessible by separate id value. It is considered best practice to create a react context outside of any component to avoid context re-creation on every render.

We can move React.createContext outside of AblyProvider if we change value stored in the context from:

type AblyContextProps = {
  client: Ably.RealtimeClient;
  _channelNameToInstance: Record<string, Ably.RealtimeChannel>;
}

to:

type AblyContextProps = Record<string, {
  client: Ably.RealtimeClient;
  _channelNameToInstance: Record<string, Ably.RealtimeChannel>;
}>

with keys in Record being provider ids (same id field used before), so it will store values like this:

{
  providerId1: {
    client,
    _channelNameToInstance: {
      'channel-name-1': {
        // ... options
      }
    },
  },
  providerId2: {
    client,
    _channelNameToInstance: {
      'channel-name-2': {
        // ... options
      }
    },
  },
  ...
}

And then AblyProvider can have something like this to update context value:

export const AblyContext = React.createContext<AblyContextProps>({});

export const AblyProvider = ({ client, children, id = 'default' }) => {
  const context = React.useContext(GlobalAblyContext);

  const value: AblyContextProps = useMemo(() => {
    return { ...context, [id]: { client, _channelNameToInstance: {} } };
  }, [context, client, id]);

  return <GlobalAblyContext.Provider value={value}>{children}</GlobalAblyContext.Provider>;
};

┆Issue is synchronized with this Jira Task by Unito

VeskeR avatar Feb 26 '24 21:02 VeskeR