78

Simple Code Reuse with React Hooks

 5 years ago
source link: https://www.tuicool.com/articles/hit/7zuaUjV
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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 make Hooks reusbale as components, so you can share, use and develop them in any of your projects. It’s a faster way to make Hooks and other React components reusbale between projects and apps. Give it a try.

VRJRjiQ.png!web

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.

EjUNZzQ.gif
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.

JjayAfq.png!web
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.

ColoredBanner

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 anarticle 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.

UBNrAr2.png!web
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.

nEZbQf6.png!web
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

this

Conclusion

In this article, we first understood what React hooks are and how we can use custom hooks for separation of concerns.

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 :pray:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK