Hello to everyone! In this piece, I’ll be covering How to use local storage in React Single-Page Application.
What is Web Storage API?
Web Storage API to store data in all browsers. It started as an HTML5 API. It’s two different ways to store in browsers: the first method is Local Storage and another method is Session Storage. This Session Storage is a separate storage area while the browser is open then continues to store data when the current browser is close clear all stored data. In this method is the Local Storage data stored after the browser is closed but the data does not expire. In this tutorial, we’ll focus on How to use local storage in React.
Local Storage is the best way to persisting user data across a browser in a react Single-Page Application. This method is really simple and powerful and local storage structure is a key and value to data stored. The local storage store your data will not expire and the local storage object can get at any time. It is support by all major browsers including IE8.
How does localStorage work?
There are four methods are using to choose from:
localStorage.setItem('myData', data);
localStorage.getItem('myData');
localStorage.removeItem('myData');
localStorage.clear();
- setItem() – Add key and value to localStorage
- getItem() – get items from localStorage
- removeItem() – Remove an item from localStorage
- clear() – Clear all item from localStorage
localStorage limitations
it is also easy to misuse it. The following local storage some limitations are:
- localStorage doesn’t store sensitive user data.
- It is limited to stored from 2 MB to 10 MB size of data depending upon the browser.
- Currently localStorage only supports strings as values
- It is synchronous which means local storage execute one after the other.
- it is quite insecure.
App.jsimport React, { useState, useEffect } from "react"; import './App.css'; export default function App() { //collect the post-list from localstorage and parse it with JSON.parse() method const postsData = JSON.parse(localStorage.getItem("posts")); //initilize our parsed data if there is no data inside our initial state will be set as empty array [] const [posts, setPosts] = useState(postsData || []); const [title, setTitle] = useState(""); const [message, setMessage] = useState(""); const handleTitle = e => { setTitle(e.target.value); }; const handleMessage = e => { setMessage(e.target.value); }; const AddPost = e => { e.preventDefault(); setPosts([...posts, { title, message } ]); //let clear the input box after adding our post setTitle(""); setMessage(""); }; const removePost = (title) => { //removePost take title as argument //let's reset the post list after filtering post title which are not equal to title setPosts(posts.filter(item => item.title !== title)); }; useEffect(() => { localStorage.setItem("posts", JSON.stringify(posts)); }); return ( <div className="Section__one"> <div className="container"> <div className="row"> <div className="local__storage"> <h1>React with local storage</h1> <form onSubmit={AddPost}> <div className="form-container"> <label htmlFor="title" className="label"> Title </label> <input type="text" value={title} onChange={handleTitle} required/> </div> <div> <label htmlFor="message" className="label"> Message</label> <textarea type="text" value={message} rows="4" onChange={handleMessage} required /> </div> <button type="submit">Add Post</button> </form> {posts.map(item => ( //remember to set the key , each item need to have a key <div className="post" key={item.title}> <h3>{item.title}</h3> <p>{item.message}</p> <span className="close__buttons"> <button onClick={() => removePost(item.title)}>X</button> </span> </div> ))} </div> </div> </div> </div> ); }
Conclusion
Finally, How to use localStorage with React tutorial is over. In this piece, we learned the basics of React hooks using localStorage API is easy.
And that’s all. If you want the full source code for the localStorage with React in our Github repository. https://github.com/CodeAT21 This link is a CodeAT21 Github repository.