A
A
alex4answ2020-06-04 16:54:53
React
alex4answ, 2020-06-04 16:54:53

Custom hooks or HOCs, when to use which?

Good afternoon, there are a bunch of components with similar functionality:

const CategoryPage = (props) => {
  const [data, setData] = useState(null);
  const { url, params: { category } } = useRouteMatch(); // #1
  
  useEffect(() => {
    CategoryService.get(params.category) // #2
    .then(res => setData(res));
  }, [category]);

  return <PageComponent data={data} />;
}


#1 - category, url parameter that will be different for each page component, for example, for the ProductPage component, not category, but product
#2 - The service for working with the API is also different for each page

decided to do it with HOC , something like this:
withPageData(HOC)

const withPageData = (Component, selectData, routeParam) => {
  return (props) => {
    const [data, setData] = useState(null);
    const { url, params } = useRouteMatch();

    useEffect(() => {
      selectData(params[routeParam])
      .then(res => setData(res));
    }, [url]);
    
    return <Component data={data} {...props} />;
  };
};

Примерно так это должно выглядеть


But then I remembered that you can create custom hooks for such purposes.
usePageData(hook)

const usePageData = (selectData, routeParam) => {
    const [data, setData] = useState(null);
    const { url, params } = useRouteMatch();

    useEffect(() => {
      selectData(params[routeParam])
      .then(res => setData(res));
    }, [url]);
  
    return data;
  }



And so the question arose before me:
When should I use HOC, and when should I use custom hooks?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Robur, 2020-06-04
@alex4answ

When to use HOC and when to use custom hooks?

If you have switched to development using hooks and want uniformity in the code, then always hooks. HOC is not needed at all.
If you like/want to file HOC and some mess in the code doesn't bother you, do HOC.
In terms of functionality and capabilities, they are interchangeable.
From the point of view of code purity, of course, when switching to hooks, HOC must be abandoned - this is just an extra concept in the application.

L
luzianin999, 2020-06-04
@luzianin999

class component => HOC, functional => hook

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question