DEV Community

TulusIbrahim
TulusIbrahim

Posted on • Edited on

Use Custom Hook to Separate Logic & UI in React

In this article, I will show you how to separate the concern between logic and UI when building react app. Let’s get started.

Have a look at below code example.

Image description

It’s a simple react counter app that works just perfectly fine. At this stage, your component will not have any problem by having two method inside it. But imagine as your component grow, the method inside it will increase, and your component will harder to debug, and so many lines in one file. This is where custom hook come in handy to separate between your logic and your actual UI.

Now let’s create another file called useCounter, since our main component called counter, or whatever you like, but the name of the function is highly recommend to have use word in front of it as it state in react docs.

In this file, we move all our method and state inside our main component to here. It would be look like code below.

Image description

We have move all our method to here, and notice that in the end, we return all the value and method that our main component will need. Now move back to our main component and import these from our custom hook like below.

Image description

Now our code will look much cleaner and readable because it’s only concern about the UI, and only import all the method and value from the custom hook. This also make the method inside the hook is reuseable for other component that need it. Thank you for reading, see ya!

Top comments (0)