Wrap usePreloadedQuery in a custom hook

Wrap usePreloadedQuery in a custom hook


1

I’m new to working with react-relay and graphql.

I’ve taken the initiative to create the custom hook below and I’m wondering if this is the correct way to do it or if it goes against the recommended practices in Relay.

From the usePreloadQuery documentation I do notice that we use it on a deeper level in the component tree, after we have the query reference thats why I am wondering if using this alltogether in a customer hook is acceptable.

Also, is it acceptable to pass null as an argument to usePreloadedQuery?

P.S. I have a concern that reading the context inside the hook might not be the best practice, but I’m not entirely certain about it either.

Here is my snippet

import React from 'react';
import { useQueryLoader, usePreloadedQuery } from 'react-relay/hooks';
import { useAppContext } from 'src/appContext';

// on src/appContext
// export const useAppContext = () => useContext<AppContextType>(AppContext);

export const useGenericQuery = (query) => {
    const { globalQueryRef } = useAppContext(); // this is React.Context
    const [queryReference, loadQuery] = useQueryLoader(query, globalQueryRef);

    React.useEffect(() => {
        if (loadQuery) {
            loadQuery();
        }
        return () => {
            queryReference?.dispose();
        };
    }, [loadQuery]);

    const data = usePreloadedQuery(query, queryReference || null);

    return {
        data,
    };
};


  [1]: https://relay.dev/docs/api-reference/use-preloaded-query/

1 Answer
1


0

Your custom hook approach doesn’t seem to violate any major Relay best practices but keep in mind the usePreloadedQuery hook is generally used deeper in the component tree, but encapsulating it in a custom hook doesn’t inherently break this pattern. Just ensure that the custom hook is used in a context where this makes sense.



Leave a Reply

Your email address will not be published. Required fields are marked *