React hooks were released back on September 26, 2017, as an essential update along with react 16. That brings a lot of useful hooks including useEffect, useState, useCallback etc. Alongside that, react also gave the power to write own custom hooks.
Why custom hooks?
Inside a react component we may have states and logic for managing states including react's built-in hooks, so before React 16 if we want to use those state and stateful logics again in some other components then we had to write those again, since states and react hooks are only allowed inside the component we can't even write the common utility function for that.
This is where React custom hook comes with React 16 to play its role, custom hooks may have their own states and stateful logic that can be used by importing them inside many components.
How to write custom hooks?
Writing custom hooks is nothing much different than writing a react component. A custom hook identifier must start with use
prefix like useFormFields
and you can start writing your own custom hook just like any other regular functional component, since it's a hook you can define states and use built-in react hooks inside that to achieve the functionality you want.
Example
Let's write a react custom hook for the form which has two fields title
and description
.
import { useEffect, useState } from "react";
export const useFormFields = () => {
const [title, setTitlle] = useState("");
const [description, setDescription] = useState("");
useEffect(() => {
console.log("title or descrotion has changed");
}, [title, description]);
const handleSave = () => {
console.log(title, description);
};
return { title, setTitlle, description, setDescription, handleSave };
};
Now we will import our custom hook inside our component and use states and methods returned from the custom hook, and we could use this in any other component as well.
import { useFormFields } from "./hooks";
import "./styles.css";
export default function App() {
//useFormFields is our custom hook to manage state and methods for this component
const {
title,
setTitlle,
description,
setDescription,
handleSave
} = useFormFields();
return (
<div className="App">
<label htmlFor="title">Title</label>
<input
id="title"
value={title}
onChange={(e) => setTitlle(e.target.value)}
/>
<label htmlFor="description">Description</label>
<input
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<button onClick={handleSave}>Submit</button>
</div>
);
}
Benefits of having custom hooks
It's not the case that you always want to have some reusable hooks, you could actually move the stateful logic of your component to a custom hook and make your component look much cleaner and small.
That is it for this blog, will see you in the next one. Happy Coding!