Build a Custom React Hook in 5 Minutes
A quick guide to custom React Hooks
A quick guide to custom React Hooks
React hooks provide an excellent way for writing React components without ever defining a class. Instead, we undertake a functional approach to creating components. This allows our code to be more modular as we are no longer dependent on lifecycle methods to split them up, but rather we split components by their use case and purpose.
If you are new to hooks, be sure to check out the overview of hooks here.
@sdolidze has published an excellent in-depth article titled “The Iceberg of React Hooks” where he covers level by level the various hooks offered by React. In this article, we will take a look at how we can create our own custom React hook.
What exactly is a custom hook?
Hooks allow us to interface, modify and update a component’s state and lifecycle. Referencing the React docs, the simplest rule of a custom hook is that it has to always start with a
use prefix. A custom hook is simply going to be like a normal function as we can decide what arguments it requires. The custom hook should also follow all the defined rules of Hooks.
The main advantage of building a custom hook is that we are able to extract our component logic into reusable functions. This makes our code more modular and “clean”.
What are we building?
One of the most common ways of persisting data in a React app is to use the local storage that comes with browsers. We can think of this as a small storage area where we can keep some simple key and value pairs to persist some data. This data can be anything from storing user profile attributes, search queries or even preferences such as the theme of the application.
Interfacing with local storage is pretty straightforward. We have two main functions:
getItem. We can use them as shown below:
// Set a key-value pair
// Retrieve value by key
Now, let’s get started. First let’s define our
useLocalStorage hook in a new file called
In this code, we are defining a new function which takes in a key and initial value and stores it in a state variable called
value. We have also defined a function called
storeValue which helps to store the function into the local storage of the browser.
Finally, we return the
value and the
storeValue function back to the caller.
Let’s use this hook in another file as follows:
Here we simply consumer the
useLocalStorage hook by importing it and giving it a key. Once the component renders, we call the
setUserId function to set a user ID of
Initialising our value from localStorage
We want to initialise our value from the local storage to see if we have any previously saved value. To do this, let’s do a lazy initialisation of our
value state in
In the above code, we have done a lazy initialisation since interfacing with local storage is a potentially expensive operation which might be slow. So we only want to initialise the value on the first run of the application.
To do so, we provide a function to the
useState hook and within it, we attempt to retrieve a key from the local storage. If there exists any value and we are able to parse it into a valid JSON, then we return that. In the event of a parsing error, or in the absence of the key, we simply return the
Finally, let’s enhance the storeValue function by converting it to an
useEffect hook and also stringifying our value before storing it.
By using the
useEffect hook and specifying
value in the dependency array, we will be able to save the value into local storage each time
value gets updated. We return
setValueback to our caller function.
That’s it! With just a few lines of code, we have created a dedicated hook to interface with the local storage of our browser. Now each time we update the variable, it is automatically persisted to the local storage. Even with browser reloads, we are able to retrieve the value from the browser’s local storage and initialise our variable.
Custom hooks can be really helpful in React apps and can simplify repetitive logic.
Happy coding! 💻
More content at plainenglish.io