Home > Software design >  React Custom Hooks - Delegating all the responsibilities to a custom hook. Anti-pattern?
React Custom Hooks - Delegating all the responsibilities to a custom hook. Anti-pattern?

Time:11-16

I am cleaning a component which listens to my db, and when it has a response, navigates to a specific screen.

This is my original component:

function MyComponent() {
   const { navigation } = useNavigation();

   const start = (data) => {
      navigation.navigate("Somewhere", { data });
   };

   const listenData = (doc) => {
      const { something } = doc.data();
      start(something);
   };

   useEffect(() => {
      const listener = listenDB((data) => {
        setData(data);
      };

      return () => listener();
   }, []);

   return ...;
}

And I am thinking to move all the logic to a custom hook useMyComponentLogic();

function useMyComponentLogic() {
   const { navigation } = useNavigation();

   const start = (data) => {
      navigation.navigate("Somewhere", { data });
   };

   const listenData = (doc) => {
      const { something } = doc.data();
      start(something);
   };

   useEffect(() => {
      const listener = listenDB((data) => {
        setData(data);
      };

      return () => listener();
   }, []);
}

and then just use it in my component:

function MyComponent() {
    useMyComponentLogic();

    return <View>...</View>;
}

With this, my hook seems to do two things:

1. Handle navigation
2. Listening to db

Is it an anti-pattern to delegate all the responsibilities (like navigating when data is listened) to a custom hook?

CodePudding user response:

I don't see this as an anti-pattern, quite the contrary, I see it as a pattern of separation of concerns.

Components are views, which should only include view, view logic, and event handler.

Each custom hook should focus on only one function and logic. For your case, it's better to create two custom hooks: useDB and useNavigation. Hooks are just js functions, good functions are compact and do only one thing.

From the doc useYourImagination()

Try to resist adding abstraction too early. Now that function components can do more, it’s likely that the average function component in your codebase will become longer. This is normal — don’t feel like you have to immediately split it into Hooks. But we also encourage you to start spotting cases where a custom Hook could hide complex logic behind a simple interface, or help untangle a messy component.

And it's easy to test for each small custom hook using react-hooks-testing-library instead of a component include a whole big thing.

I use this architecture, and it works well React & Redux Application Architecture

  • Related