Using Custom Hooks to Separate Concerns in React Components

Nina Loeterman
2 min readJan 13, 2021
Photo by Oliver Hale on Unsplash

Keeping code clean is important in every programming language. In React, separating UI, logic, and styles drastically improves readability in your code by keeping it clean. Using custom hooks is a great way to manage state and functionality outside of the UI. It’s a technique that I love because it seamlessly separates concerns making for cleaner code.

Custom hooks are a great way to create reusable functions in React. It can be a great thing for a project to have a useAPI hook, or a useResize hook, but we can also use custom hooks in situations where there is a lot of specific component logic in order to improve readability of the component.

Below is an example of a card component that is being presented with film data (using swapi.dev api of star wars films). This is how our component looks with the logic inside the main component:

Extract All Logic (State and Functions) to the Hook

Here we create a new function called useCard, initiating our custom hook. Be sure to call this function use before the function name so that we know it’s a hook. Transfer all state management and functions to the hook, and return the functions and states that you need access to in the component/s that will use the hook. The hook will look something like this:

Use the Hook in Your Component

Next we use useCard and deconstruct the function and state that are needed for the UI. I also pass film to the hook as an argument so that it can be accessed in the hook (check it out in the previous code snippet). You can pass as many arguments here as you need.

A Word About File Structure

For situations like the above, I like to structure my component like so:

├── components
│ ├── Card
│ │ ├── Card.jsx (UI goes here)
│ │ ├── Card.logic.jsx (custom hook goes in here)
│ │ └── Card.styles.css (styling goes in here)

And there you have it!

Keeping organized is important, even for small projects. This is a small example, but custom hooks can be reusable, and/or deal with much more intricate logic of components.

If you want to check out the full example that I present in this article, you can find it here:

Also, be sure to check out the official React docs, they really say it the best!

--

--