0

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

...
  • Please post the part of your app code that interacts with the localstorage, as well as where exactly you are doing the logging – Bergi Jul 15 '23 at 14:08
  • 1
    It's the `localStorage.setItem("comments", …)` effect that sets the localstorage to the initial value of `comments`, which is an empty array. The `getItem` effect that is running twice just exposes this. Congratulations, strict mode has found a bug in your code! – Bergi Jul 15 '23 at 14:23

1 Answers1

0

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.

raina77ow
  • 103,633
  • 15
  • 192
  • 229