Use localStorage
Follow step-by-step instructions to use localStorage in the project.
We'll cover the following
Set the items
We must save the item each time the status of our toDoList
changes (by adding new items or deleting old ones). We have useEffect
in React to help us out. It takes two arguments:
- The
function
argument is called by using a hook. - The
dependency
argument preventsuseEffect
from rendering each time. It only allows it to render when there’s adependency
change. In our case, thedependency
istoDoList
.
The syntax for the useEffect
hook is the following:
useEffect ( function , [ dependency] )
In our case, the key
is TASK
and the value is stringifyToDoList
.
Because localStorage
saves data in JSON format and JSON.stringify
converts objects to JSON, we use JSON.stringify
.
useEffect(() => {
const stringifyToDoList = JSON.stringify(toDoList)
localStorage.setItem("TASK", stringifyToDoList );
}, [toDoList]);
Get hands-on with 1400+ tech skills courses.