Before removing strictmode
index.js
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
console.log(localStorage.getItem("comments")
[{"name":"1","comment":"asdjflisadhj"}]
[]
removing strictmode
index.js
...
root.render(<App />);
...
console.log(localStorage.getItem("comments")
[{"name":"1","comment":"asdjflisadhj"}]
Local storage finally did it normally. But I wonder why strict mode initialized local storage.
const Info = () => {
const [name, setName] = useState("");
const [comment, setComment] = useState("");
const [comments, setComments] = useState([]);
useEffect(() => {
const savedComments = localStorage.getItem("comments");
if (savedComments) {
setComments(JSON.parse(savedComments));
}
console.log(localStorage.getItem("comments"));
}, []);
useEffect(() => {
localStorage.setItem("comments", JSON.stringify(comments));
}, [comments]);
...
There's nothing special about how StrictMode uses localstorage. What is special is intentionally calling several functions, that are expected to be pure, twice - which that might be the real root cause in your case. Quoting the docs: