Skip to content

New composable React hooks #53

@jaydenseric

Description

@jaydenseric

Currently, the useGraphQL React hook does a lot, which is not desirable for a few reasons:

  1. It's hard to test. With so many options interacting with each other, every option variation needs to be tested with most of the variations of the other options.

  2. Options have a performance cost regardless if they are being used. For example, the loadOnReset option utilizes a React.useCallback and a React.useEffect:

    /**
    * Handles the [`GraphQL`]{@link GraphQL} [`reset`]{@link GraphQL#event:reset}
    * event.
    * @param {GraphQL#event:reset} event Event data.
    * @ignore
    */
    const onReset = React.useCallback(
    ({ exceptCacheKey }) => {
    if (cacheKey !== exceptCacheKey && isMountedRef.current) {
    ReactDOM.unstable_batchedUpdates(() => {
    setCacheValue(graphql.cache[cacheKey]);
    setLoadedCacheValue(graphql.cache[cacheKey]);
    });
    if (loadOnReset) load();
    }
    },
    [cacheKey, graphql.cache, load, loadOnReset]
    );
    React.useEffect(() => {
    graphql.on('reset', onReset);
    return () => {
    graphql.off('reset', onReset);
    };
    }, [graphql, onReset]);

  3. The code supporting options increases the bundle size, regardless if the options are even being used.

  4. If a consumer wants to subscribe to the GraphQL events for their own custom purposes using React.useEffect (e.g. to do something in a callback if cache is reloaded while the component is mounted) they have to reinvent wheels that are already implemented inside useGraphQL.

I won't be sure of the final design for the hooks without a lot of work that might also depend on some big changes to the GraphQL client API as well as the SSR API, but here is one idea:

const onGraphQLReset = React.useCallback(
  ({ exceptCacheKey }) => {
    if (cacheKey !== exceptCacheKey) load();
  },
  [load]
);

useOnGraphQLReset(onGraphQLReset);

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