How to Separate Logic & UI in React Using Custom Hook

How to separate the concern between logic and UI when building a React app.

Tulusibrahim
JavaScript in Plain English

--

Photo by Sean Oulashin on Unsplash

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

Have a look at below code example:

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 methods inside it. But imagine as your component grows, the methods inside it will increase, and your component will be harder to debug, and there would be so many lines in one file. This is where a custom hook comes in handy to separate your logic and your actual UI.

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

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

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

Now our code will look much cleaner and more readable because it’s only concerned about the UI, and only imports all the methods and values from the custom hook.

Thank you for reading. See ya!🍻

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Check out our Community Discord and join our Talent Collective.

--

--