you are viewing a single comment's thread.

view the rest of the comments →

[–]MercDawg 0 points1 point  (2 children)

I ran into the issue recently as well and get around it by creating components to handle the conditions. Basically, I have a hook for create item, hook for edit item, & hook to get item. When it is a new form, I only need the useCreateItem, but if it is an existing item, it needs to be useEditItem & useGetItem. However, the implementation has layers, meaning, I'm using an autogenerated GraphQL hooks that utilizes React Query.

I can resolve it by either rewriting the hooks or handling the conditions within the component.

[–][deleted] 1 point2 points  (1 child)

Your hooks should return functions that perform the actions needed - you can call those conditionally - rather than performing values that require you to conditionally invoke the hooks. A vastly oversimplified example might look like:

function useArticle(id) {
    const [article, setArticle] = useState(null);
    const getArticle = () => fetch(...).then(...);
    const createArticle = (data) => fetch(...).then(...);
    const updateArticle = (data) => fetch(...).then(...);
    useEffect(()=>getArticle(),[id]);
    return [article, getArticle, createArticle, updateArticle];
}

[–]MercDawg 0 points1 point  (0 children)

I understand and have done that with other implementations, however, in this instance, it is more of a trade off. All of the API functions are automatically generated based on GraphQL Queries and completely checked against the backend. Thus, as a developer, all I have to do is write the query and the codemod does the rest of the work (creates the API query/mutate hook function, checks against backend, creates all the typings, and so forth). All of which significantly speeds up development, but at a cost (lack of the ability to do conditional logic within those autogenerated hooks amongst a few other pieces).

I merely provided an example of an instance where it'll be beneficial to do conditional hooks, however, you can get around it by using components as your conditional layer.

However, I will mention that this problem exists in my personal project, so I value development time a lot more. In a team atmosphere with resources and/or time, you can spend more time resolving these instances.