Why react strictmode initializes localstorage

92 Views Asked by At

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]);

...
1

There are 1 best solutions below

0
On BEST ANSWER

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:

React assumes that every component you write is a pure function. This means that React components you write must always return the same JSX given the same inputs (props, state, and context).

Components breaking this rule behave unpredictably and cause bugs. To help you find accidentally impure code, Strict Mode calls some of your functions (only the ones that should be pure) twice in development. This includes:

  • Your component function body (only top-level logic, so this doesn’t include code inside event handlers)
  • Functions that you pass to useState, set functions, useMemo, or useReducer
  • Some class component methods like constructor, render, shouldComponentUpdate

[...]

When Strict Mode is on, React will also run one extra setup+cleanup cycle in development for every Effect. This may feel surprising, but it helps reveal subtle bugs that are hard to catch manually.