useEffect.dev
← Back to lessons

Lesson 3. Custom hooks and classic async pattern 3. Good practices with custom hooks

Custom hooks are an elegant way to extract some behavior from a component and even make it reusable across components. Some practices will help you write consistent hooks and make the other developers happier using your hooks.

First, remember that hooks are plain functions, so all the good practices you can imagine for splitting the code into functions will apply with hooks too. For instance:

  • Make your hooks as small as possible. If possible, each hook should be responsible for one behavior, and if needed, you can still compose several small hooks to create a new one bigger and more specific.
  • Name your hooks accordingly to what they do. Also, you need to prefix all your hooks’ name with use, as it’s a convention imposed by React.

Additionally, when possible, you should respect the conventions of hooks provided by React. For instance, if one of your hooks returns a value and a setter, it’s a good idea to return them as useState does: an array [value, setValue]. Save other developers some struggle, don’t invert the two elements of the array.

In the next lesson, we’ll see that hooks come with rules that you have to respect. And, of course, these rules stand for your custom hooks too.

Where should I put my custom hooks?

How to organize files in a React project is a recurring one since there is no consensus on a convention, and React lets you free to do as you want. Here is how I organize my files when I write custom hooks; take it as a suggestion.

First thing, I prefer putting my components in a dedicated folder in my project. It’s also a common practice to make a distinction between container components (with local state, or connected to a Redux store) and other components used for rendering, without any state nor side effect. For small applications, though, this distinction is not always relevant.

So here is how files in a React project can be organized:

+ src/
+ components/
+ Component1.js
+ Component2.js
+ container/
+ Container1.js
+ Container2.js
+ helpers/
+ services/
+ etc.

When adding custom hooks, the easiest is to put them in a new folder at the same level:

+ src/
+ components/
+ containers/
+ hooks/
+ hook1.js
+ hook2.js

Now, should you put all your custom hooks in this hooks directory? It depends on how reusable and generic the hook is. A very generic hook can be in this directory so all the components can use it easily.

But sometimes, it can be useful to create a custom hook to extract some logic of a component without making it reusable. You will still get the advantages of a custom hook (separating concerns, making it testable), but it doesn’t mean you have to make it generic. In that case, you can leave it in the same directory as the component(s) using it, even in the same file.