Introduction
In this lab, we will be exploring the useLocalStorage hook in React. The purpose of this lab is to help you understand how to create a stateful value that is persisted to localStorage and a function to update it. You will learn how to use the useState hook, try-catch block, and Storage.getItem() and Storage.setItem() methods to store and retrieve data from localStorage. By the end of this lab, you will have gained a better understanding of how to build React applications that utilize localStorage to store and persist data.
React useLocalStorage Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
This function creates a value that is saved to localStorage and a function to modify it. Here's how it works:
- To create the value, use the
useState()hook with a function to initialize it lazily. - To retrieve the saved value from
localStorage, use atry...catchblock andStorage.getItem(). If there's no saved value, useStorage.setItem()to store thedefaultValueand use it as the initial state. If there's an error, usedefaultValue. - Define a function that updates the state variable with the passed value and uses
Storage.setItem()to save it.
Here's the code:
const useLocalStorage = (keyName, defaultValue) => {
const [storedValue, setStoredValue] = React.useState(() => {
try {
const value = window.localStorage.getItem(keyName);
if (value) {
return JSON.parse(value);
} else {
window.localStorage.setItem(keyName, JSON.stringify(defaultValue));
return defaultValue;
}
} catch (err) {
return defaultValue;
}
});
const setValue = (newValue) => {
try {
window.localStorage.setItem(keyName, JSON.stringify(newValue));
} catch (err) {}
setStoredValue(newValue);
};
return [storedValue, setValue];
};
You can use this function in your app like this:
const MyApp = () => {
const [name, setName] = useLocalStorage("name", "John");
return <input value={name} onChange={(e) => setName(e.target.value)} />;
};
ReactDOM.createRoot(document.getElementById("root")).render(<MyApp />);
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the React useLocalStorage Hook lab. You can practice more labs in LabEx to improve your skills.