Member-only story
Creating Reusable Components with React Hooks
In React, we need to keep our code DRY (don’t repeat yourself), so we need to reuse our components instead of making multiples. It would be redundant to make four or five components in our codebase called “ButtonBlue.js”, “ButtonPink.js”, and “ButtonPurple.js”. Being able to reuse components is one of the largest draws of using a framework like React.
The React Hooks API is a component design pattern that allows for using a state (was the button clicked? How many times?), preform side effects, and hook into a component’s lifecycle. This is now supported by functional components, when previous React releases only allowed this in class components.
In this tutorial, I’ll show you how I manage multiple design states on a single Buttons.js component. Please note that I have used the nomenclature of “Buttons” because I often use MUI and they already use “Button” as a component.
You can follow along with my CodeSandbox link:
https://codesandbox.io/s/creating-reuseable-components-with-react-hooks-zyiprq
- The first item of business is to determine what types of variants of buttons we need. For this exercise we are going to make variants of buttons that will have different sizes, shapes, interactivity, and colours.