Creating custom React hooks allows you to encapsulate and reuse logic in your components. Custom hooks are functions that use other React hooks internally. Here’s a simple example of creating a custom React hook:
Example: UseLocalStorage Hook
Let’s create a custom hook named useLocalStorage
that allows you to read from and write to the browser’s local storage.
// useLocalStorage.js
import { useState } from 'react';
const useLocalStorage = (key, initialValue) => {
// Retrieve the stored value from local storage or use the initial value
const storedValue = localStorage.getItem(key);
const initial = storedValue ? JSON.parse(storedValue) : initialValue;
// State to hold the current value
const [value, setValue] = useState(initial);
// Update local storage whenever the value changes
const setStoredValue = (newValue) => {
setValue(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
};
return [value, setStoredValue];
};
export default useLocalStorage;
How to Use the Custom Hook
Now, you can use your useLocalStorage
hook in any component:
// MyComponent.js
import React from 'react';
import useLocalStorage from './useLocalStorage';
const MyComponent = () => {
// Use the custom hook to get and set a value in local storage
const [username, setUsername] = useLocalStorage('username', 'DefaultUser');
return (
<div>
<p>Username: {username}</p>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
);
};
export default MyComponent;
In this example, useLocalStorage
is a custom hook that abstracts away the logic related to local storage. The hook takes a key and an initial value as parameters and returns an array containing the current value and a function to update that value.
When you use the useLocalStorage
hook in your component, you get access to the current value (username
) and a function (setUsername
) to update that value. The local storage is automatically updated whenever the value changes.
This is a basic example, and you can create more complex custom hooks based on your specific needs, combining multiple built-in hooks, or even using other custom hooks within your custom hook.