Local Storage is used for storing data on the client side i.e. in the memory of the browser. There's a 'session storage' that can also be used for the same purpose of storing but it gets deleted once the tab is closed or once the session is expired.
The data can be persisted even after the page reload unless and until the user does not delete it in case of local storage. Hence we can use it to store some information about the user like-
Dark mode preferences
Form Input values of the user
Previous values entered in the input box
Local storage has a maximum limit of 5MB and can vary depending on the browser.
It can retain the data even after the application stops and on the browser reopen as well. The data is stored in a key-value format in the form of strings.
we can create a state with the useState hook and can store it in the localstorage object as below.
const [tasks, setTasks] = useState("")
First, define a state named 'tasks' and the function to manipulate the state as 'setTasks' as shown.
return (<div>
<form>
Name:
<input type="text" value={tasks} onChange={(e) => changeHandler(e)} name='tasks'></input>
<button type='button' onClick={() => saveTasks()}>Submit</button>
</form>
<hr />
Names : <br />
{taskList.map(res => res)}
</div>)
The JSX for the component would have a form and the input field with a change handler and a function to save the tasks as shown above.
const changeHandler = (e) => {
console.log(e.target.value)
if (e.target.value !== "") {
setTasks(e.target.value)
}
}
The 'onchange' event will get triggered on every value change for the input placeholder. So, the function to the handler that event is defined as above and in that the value can be read by the event object. This value can be set to the 'tasks' state using the setTasks method.
const [taskList, setTaskList] = useState([]);
Once the tasks are set we have to maintain a task list that will have all the tasks mentioned. So, we should define another state with empty array initialization.
const saveTasks = () => {
if (tasks !== "") {
setTaskList([...taskList, tasks])
setTasks("")
localStorage.setItem("tasks", JSON.stringify(taskList))
}
}
Now, we have to save all the tasks in the taskList array and for that, we have to call this function on the button. Here, as we are dealing with the array data type so we should consider the previous value of the array. Thus, we can do that with the rest operator that combines the two arrays or an array with another object.
Also, the task input should be cleared for the new value, hence its again set to the blank value by calling its setTasks function.
Finally, we can access the localStorage object and set the value with a key named "tasks" with the stringified object as shown. As we are using an array so it has to be stringified to store.
useEffect(() => {
const retrievedTasks = JSON.parse(localStorage.getItem("tasks"))
if (retrievedTasks && retrievedTasks.length > 0) {
console.log("retrievedTasks", retrievedTasks)
setTaskList(retrievedTasks)
console.log("localStorage", localStorage)
}
}, [])
Once we reload the page, we should retrieve the data from the localStorage directly. So for that, this hook useEffect gets called on every first reload.
There's a blank array as the second parameter is passed that makes sure to call it once.
Once we get the data from the storage, again it has to be parsed back to the Object format and set to its state 'tasksList' as shown.
You can refer to the example snippet as shown.
Boom! It's ready now. You can reload the page and the data will be persisted until you clear your browser cache or local storage. Keep learning, Happy Coding :)