React.js provides the flexibility to create custom hooks that encapsulate reusable logic. In this section, we will walk through the steps to create a custom hook for handling local storage interactions. Let’s call it useLocalStorage.
Step 1: Create useLocalStorage Custom Hook
In a new file, let’s name it “useLocalStorage.jsx,” start by importing the necessary dependencies:
import { useState, useEffect } from 'react';
Next, create the useLocalStorage hook:
function useLocalStorage(key, initialValue) { const [value, setValue] = useState(() => { const storedValue = localStorage.getItem(key); return storedValue ? JSON.parse(storedValue) : initialValue; }); useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue]; } export default useLocalStorage;
Inside the useLocalStorage
hook, we use the useState
hook to manage the state of the stored value. The initial state is set by retrieving the value from localStorage
using the provided key. If no value is found, the initialValue is used.
The useEffect
hook is utilized to update the local storage whenever the stored value changes. It listens for changes in both the key and value dependencies. Upon change, it updates the local storage using localStorage.setItem()
.
Finally, the useLocalStorage
hook returns an two elements: the current value and a setter function. The calling component can use these values to access and modify the stored data.
Step 2: Implement the Custom Hook
Now, let’s use the custom useLocalStorage
hook in a component. In your desired component file, import the hook:
import useLocalStorage from './useLocalStorage'; function MyComponent() { const [name, setName] = useLocalStorage('name', 'John Doe'); // Use the name state variable and setName function as needed return ( // JSX for your component ); } export default MyComponent;
In this example, we use the useLocalStorage
hook to create a state variable called “name.” The first argument is the key used to identify the stored value in the local storage. The second argument is the initial value to be used if the key is not found.
The returned “name” state variable and “setName” function can be used like any other state in React. Any changes to “name” will automatically update the local storage, ensuring the data persists across page reloads and browser sessions.
Conclusion:
By creating a custom hook for local storage interactions, such as useLocalStorage
, we can simplify and streamline the process of persisting and retrieving data in React.js applications. This approach abstracts away the complexities of the local storage API and enables developers to focus on building powerful and user-friendly features.
Feel free to extend and customize the useLocalStorage hook to fit your specific needs, such as adding validation, handling multiple values, or implementing more advanced storage strategies. With custom hooks like useLocalStorage, React.js empowers developers to create robust and efficient applications that leverage the capabilities of local storage seamlessly.
Want to learn more about custom hooks creation? Reffer to our tutorial on how to create useDebounce hook.
0 Comments