Simple Code Reuse with React Hooks

Aditya Agarwal
Bits and Pieces
Published in
7 min readNov 20, 2018

--

Code reuse is very necessary for scaling. We’ll be looking at what React hooks are and how we can use them to keep our components D.R.Y.

What are React Hooks?

Hooks are a new feature proposal that lets you use state and other React features without writing a class. They’re currently in React v16.7.0-alpha and being discussed in an open RFC. So it is not recommended to use them in production.

Why is everyone talking about React Hooks?

React hooks are nothing less than a revolution in the React world. They simplify so many things. Need state but hate classes or confused by this ? No problem, hooks got your back. And not just that, hook also lets you reuse code in an elegant manner too. But wait…

What do we mean by “reusability”?

A React component is used to encapsulate logic, markup, and design of a piece of UI. There comes a situation where two or more components need some common functionalities but differ in how they use it.

An example of that would be tab switcher and accordion components. Both of these components need to show one panel at a time and hide others. Based on user input (gesture, click, key press, etc.) they have to change which panels are hidden and which are shown. But both the components differ greatly in how they look and behave. Tabs are for switching between different parts of application whereas an accordion is to get an overview of all the points related to one section and then having an option to see any point in detail.

What we can observe is that both the components are dealing with more than one concern. The logic to select which panel to hide and which to show is a separate concern and the way user views and interact with it is a separate concern. The former concern is what we call a cross-cutting concern and we can abstract it into an independent module. This way both the components can use the same module and focus on their main concerns.

React hooks provide a very convenient way to implement cross-cutting concerns which help in code reuse. But first, let’s look at a simple example of a React component with Hooks.

Tip: Use Bit to organize and reuse components. It works with React hooks too, so you can share a collection of your hooks and reuse them as needed. Major time saver, and useful for your team. Give it a try.

KKKKReact spinners with Bit

Example: Building a color changing banner

There is a banner having some text and a button to change the background color of the banner. Let’s call it ColoredBanner . The end result should be like this.

Clicking on Change button changes the background color

It’s obvious we need some state to hold the current background color and an event handler to change the state. Before hooks, the only way to accomplish this task was with classes. We’d use this.state and this.setState() to refer and update state respectively. Let’s look at how to do it with React Hooks.

ColoredBanner-1.js

We have an array of colors between which the background color would alternate. Next, we call the useState() method provided by React. This is a React hook which lets us use state inside functional components.

The useState() method uses the passed argument as initial state. Since we have passed ‘red’, the background color will be red initially. The hook then returns an array containing two items. We destructure it and so the first item called color holds the current color state. The second item setColor() is a method to change the color state.

We then define a changeColor() function which randomly picks one color from the colors array and then use the setColor() method to update the state to the new color.

At last, we return the markup in which we set the button’s click handler to changeColor() function. So everytime user clicks on the button, changeColor() function is called which then changes the background color.

Need for separation of concerns

Suppose next we need to make another component which has the same changing background feature but instead of the user clicking the button, we want the background to automatically change after a set interval. Now we can observe some things.

  1. We can’t directly use ColoredBanner component because it is using event handler.
  2. We just want the part which randomly picks a color and change the state.

It is clear that changing of color randomly and the way it is used are separate concerns. The first thing is needed in both the components but the latter is only used in the ColoredBanner component. Had this component not mixed both the concerns together, we could just reuse that code. To do this we had to resort to patterns like Higher Order Components and Render Props. I recently wrote an article on that also.

Separation of concerns with Hooks

As we have understood why we need a separation of concerns in React components, let’s now look how to do it with React Hooks.

React allows us to make Custom Hooks with which we can implement cross-cutting concerns. This is how a custom hook for random color change can be made.

useRandomColor.js

Keeping with the React conventions, we make a function called useRandomColor() . This function is accepting two arguments, colors array and initialColor . Just like before we call the useState hook and define a changeColor() function to change the color state to random color from colors array. In the end we return an array of two items. The first item is to refer the current color and the second item is a function to change state. Returning an array is not a convention though, an object containing both the items as keys can be returned too.

Next, let’s look at how we can use this custom hook in the ColoredBanner component.

ColoredBanner.js

Here we define a colors array and pass the appropriate arguments to useRandomColor custom hook. Then we destructure the returned array and use it just like we would use any other hook.

Now if we want to implement the automatic color changing component we just need to make a component in which the changeColor method is wrapped inside a setInterval callback.

Advantages of React Hooks

  • Custom hooks are just functions and so it is very easy to understand what they are doing.
  • No need to deal with this . It becomes a pain to bind functions when we need to use them as event handlers.
  • The syntax is much shorter and that means less surface area for bugs to hide.
  • The state is now more granular. Instead of one big state object, we can have a number of small hooks and each deals with its own separate state and our components use all of them together. This way we avoid merging the new state with old state and prevent unnecessary overwrites.

With hooks we are creating functions on every render. This is not at all slow in modern browsers. Please read this Twitter thread for details and my reply to this comment on how we can optimize it if we absolutely have to.

Conclusion

In this article, we first understood what React hooks are and how we can use custom hooks for separation of concerns. To experiment with hooks on your own, please fork this codesandbox.

Feel free to comment, suggest ideas and add your own insights! You can follow me on Twitter and Medium or subscribe to my newsletter to get updates on my latest content. Thanks for reading 🙏

--

--