Reputation: 374
So what im asking is there some kind of style guide for writing react functional components with hooks. Sometimes I work with components which includes different kind of hooks:
Example (this is not my real code example, just for understanding):
import React, { useMemo, useEffect, useCallback } from "react";
import { useRouter } from "next/router";
import { useMediaQuery } from "react-responsive";
import { useCategory, useProducts} from "@hooks";
export const Category: React.FC<CategoryProps> = () => {
const foo = useMemo(() => (
// some logic here..
), []);
const { query } = useRouter();
const { category, loading: categoryLoading } = useCategory(query.slug);
const isDesktop = useMediaQuery({ query: "(min-width: 1280px)" });
const handleFoo = useCallback(() => {
// some logic here...
}, []);
const { products, loading: productsLoading } = useProducts(category.id);
useEffect(() => {
// some logic here...
}, []);
return (<h1>Some big template here...</h1>);
}
I'm struggling to find some kind of information about how to place (sort) hooks inside components. A few questions:
I know that is simple answer to that question is just to be consistent, but I want to know, what react community thinks, how you write your functional components with hooks?
Upvotes: 1
Views: 1214
Reputation: 138
After looking through the React Documentation, I found a couple rules in regards to hooks: https://reactjs.org/docs/hooks-rules.html#:~:text=Instead%2C%20always%20use%20Hooks%20at,multiple%20useState%20and%20useEffect%20calls.
Also this article: https://blog.bitsrc.io/best-practices-with-react-hooks-69d7e4af69a7
The second articles gives a good list of best practices when it comes to React Hooks.
1.) Class based components have a more structured order do to all of the lifecycle methods that you are working with componentDidMount
ect.
2.) When it comes to a functional component, then the order/structure really is not enforced. From the article:
It’s recommended to first declare state variables with useState hook, then write the subscriptions with useEffect hook followed by any function relevant to the component’s job. Then finally, you return the elements to be rendered by the browser...
In other words, what makes sense you as a developer will probably be alright. If this is a project that you are doing with other developers. Developing a coding type standard based on your work might be a good idea.
Let me know if that answers your question :)
Upvotes: 1