LocalStorage in React Using Custom Hook | The Complete React Course | Ep.41

3 min read 9 months ago
Published on Sep 08, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Introduction

This tutorial will guide you through using LocalStorage in a React application by creating a custom hook. LocalStorage allows you to store data in the browser, making it accessible across sessions. This is particularly useful for persisting user preferences or application state. By the end of this tutorial, you'll have a reusable custom hook to manage LocalStorage in your React projects.

Step 1: Setting Up the React Application

To get started, ensure you have a React application set up. If you haven't created one yet, follow these steps:

  1. Open your terminal.
  2. Use Create React App to generate a new project:
    npx create-react-app my-local-storage-app
    
  3. Navigate to your project directory:
    cd my-local-storage-app
    

Step 2: Creating the Custom Hook

Now, let’s create a custom hook to manage LocalStorage.

  1. Inside your src folder, create a new folder named hooks.

  2. In the hooks folder, create a file named useLocalStorage.js.

  3. Add the following code to useLocalStorage.js:

    import { useState } from 'react';
    
    const useLocalStorage = (key, initialValue) => {
        const [storedValue, setStoredValue] = useState(() => {
            try {
                const item = window.localStorage.getItem(key);
                return item ? JSON.parse(item) : initialValue;
            } catch (error) {
                console.error(error);
                return initialValue;
            }
        });
    
        const setValue = (value) => {
            try {
                const valueToStore = value instanceof Function ? value(storedValue) : value;
                setStoredValue(valueToStore);
                window.localStorage.setItem(key, JSON.stringify(valueToStore));
            } catch (error) {
                console.error(error);
            }
        };
    
        return [storedValue, setValue];
    };
    
    export default useLocalStorage;
    

Explanation of the Custom Hook

  • useState: Initializes state with a function that retrieves the value from LocalStorage.
  • setValue: Updates the state and LocalStorage when a new value is set.

Step 3: Using the Custom Hook in a Component

Now that you have your custom hook, let's use it in a React component.

  1. Open src/App.js.

  2. Import the custom hook at the top of the file:

    import useLocalStorage from './hooks/useLocalStorage';
    
  3. Create a simple component that uses the hook:

    import React from 'react';
    import useLocalStorage from './hooks/useLocalStorage';
    
    const App = () => {
        const [name, setName] = useLocalStorage('name', '');
    
        return (
            <div>
                <h1>LocalStorage in React</h1>
                <input
                    type="text"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="Enter your name"
                />
                <p>Your name is: {name}</p>
            </div>
        );
    };
    
    export default App;
    

Explanation of the Component

  • The input field allows users to enter their name, which is stored in LocalStorage.
  • As the user types, the state updates, reflecting changes in real-time.

Step 4: Testing the Application

Now it’s time to test your application:

  1. Run the application with:
    npm start
    
  2. Open your browser and navigate to http://localhost:3000.
  3. Enter your name in the input field. Refresh the page to confirm that the name persists.

Conclusion

In this tutorial, you learned how to create a custom hook for managing LocalStorage in a React application. This hook allows for easy data storage and retrieval, enhancing user experience by preserving application state. As a next step, consider expanding the hook to handle more complex data types or integrating it with other parts of your application. Happy coding!