React Custom Hooks
They are more powerful than you realize.
React is slowly taking over front-end development. It effectively tackles the various challenges in building large-scale applications and delivers consistent quality with clear structure and optimum performance. Hooks are a state-of-the-art technology in React which was released with version 16.8. Having long been in the comfort zone of working with class components, one might get a little edge while switching to Hooks. But, once you get used to it, Hooks inevitably grow on you.
Hooks help you create reusable, scalable and versatile functional components. By now, you might have already played around with them in your projects. If you haven’t, start today! Begin small by experimenting with them — sooner or later you will have to take the plunge into Hooks.
Why Custom Hooks?
Hooks not only allow the usage of state variables and lifecycle methods inside the functional components, but is also is a way of programming and a mechanism to separate stateful logic, and reuse it in various places in our application. The alternative approaches for sharing stateful logic between components are:
- Render Props
- Higher Order Components
But, with Hooks it is simpler and cleaner. Hooks always let you use functions instead of having to constantly switch between functions, classes, hoc and render props.
Custom Hooks are a powerful concept — they allow simplification of complex React application
Consider a situation where you have two different components which use exactly the same logic. In that case, you can create a third component to store the stateful logic there and reuse it in the first and the second component. The third component here will be your Custom Hook. If you aren’t familiar with Hooks, checkout the following article to get the basic idea on how to use Hooks and why we need them.
Custom Hooks
Custom Hooks are normal javascript functions, which can access other Hooks inside it, and hold stateful logic that can be reused within many components.
Here are a few things to keep in mind while writing Hooks:
- The name of the Custom Hook must always begin with use, so that the rules of Hooks apply to it.
- Make sure to call other Hooks at the top level of your Custom Hook.
Let’s create a few simple Custom Hooks of our own.
useInput
Take a look at the code below. This component has two state variables which use useState and updater functions for both the fields. Both of the updater functions use the same logic.
import React, { useState } from “react”; import TextField from “@material-ui/core/TextField”; import Button from “@material-ui/core/Button”; const Form = () => { const [email, setEmail] = useState(“”); const [password, setPassword] = useState(“”); const handleOnClick = () => { console.log(“email, password”, email, password); }; return ( <div> <div> <TextFieldid=”standard-name”label=”Email”value={email}onChange={(e)=>setEmail(e.target.value)}/> </div> <div> <TextFieldid=”standard-name”label=”Password”value={password}onChange={(e)=>setPassword(e.target.value)}/> </div> <Button variant=”contained” onClick?={handleOnClick}>Submit</Button> </div>); }; export default Form;
Take out the repetitive updater function and store it in the new Custom Hook. This is a useInput hook which stores and updates state variables. A useInput hook returns the variable that stores the data and also the function to update it.
import { useState } from “react”; export const useInput = initial => { const [value, setValue] = useState(initial); const onChange ?= e => { setValue(e.target.value); }; return {value, onChange}; };
Using useState hook in the form component will look like this.
import React from “react”; import { useInput } from “./useInput”; import TextField from “@material-ui/core/TextField”; import Button from “@material-ui/core/Button”; const Form = () => { const [email, setEmail] = useInput(“”); const [password, setPassword] = useInput(“”); const handleOnClick = () => { console.log(“email, password”, email, password); }; return ( <div> <div> <TextFieldid=”standard-name”label=”Email”value={email}onChange= {setEmail}/> </div> <div> <TextFieldid=”standard-name”label=”Password”value={password}onChange={setPassword}/> </div> <Button variant=”contained” onClick?={handleOnClick}>Submit</Button> </div>); }; export default Form;
useToggle
The useToggle Custom Hook toggles the value of the variable every time it is triggered. The useToggle returns an array of the state variables and also the function to toggle the variable.
import { useState } from “react”; export const useToggle = initial => { const [status, setStatus] = useState(initial); const onClick ?= () => { setStatus(status => !status);};return [status, onClick]; }; return [status, onClick]; };
This is how the useToggle component can be used within a component.
import React from “react”; import { useToggle } from “./useToggle”; import Button from “@material-ui/core/Button”; const Toggle = () => { const [status, setStatus] = useToggle(false); return ( <Button variant=”contained” onClick?={setStatus}>{status ? “On” : “Off”} </Button> ); }; export default Toggle;
Note: Two Hooks using the same Custom Hook don’t share the state.
Each call to a Custom Hook gets an isolated state. Custom hooks are treated in the same way as the useState or the useEffect. Custom hooks can be called several times in the component and each call will remain independent.
Hooks lets you manage the state more easily. The code is significantly simplified and more readable. It is easier to extract stateful logic and share them in the application. This is barely scratching the surface of what Hooks can do. Hooks are more powerful and have a lot to offer.
Sounds interesting? Hooks are just one of the many cutting-edge technologies that we extensively use at FORMCEPT. To know more about the technologies underlying our flagship product MECBot, please take a look at our product architecture here:https://www.mecbot.ai/platform/
If you would like to solve some of the most challenging data problems with our team, apply here: https://angel.co/company/formcept/jobs