1

// Is React.StrictMode is supposed to run the code twice updating any state twice initially. If not so then why am I having such a problem?

// index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);

// App.js

import { useEffect, useState } from "react";

const App = () => {
    const [arr, setArr] = useState([]);

    useEffect(() => {
        setArr((prev) => [...prev, 1]);
    }, []);

    return (
        <div>
            {arr.map((value) => {
                return <p>{value}</p>;
            })}
        </div>
    );
};

export default App;

// Expected output in console: [1]

// but getting: [1,1]

// THIS MEANS THAT STRICT MODE IS UPDATING arr FROM []->[1]->[1,1], BUT IT SHOULD ONLY RUN ONCE AT INITIAL RENDER. AND WHEN I RUN WITHOUT THE StrictMode IT GIVES ONLY [1] AS OUTPUT, WHICH IS THE EXPECTED OUTPUT.

  • 2
    This is well documented. https://react.dev/reference/react/StrictMode#fixing-bugs-found-by-double-rendering-in-development Your effect is impure. – adsy Jun 23 '23 at 18:09
  • But how do I make it pure, I can't understand. Please can u confirm by correcting the above? Because I am new to react and having difficulty in understanding this pure effect thing – Chandra Chud Singh Chundawat Jun 23 '23 at 18:37
  • I suspect your code is toy code to prove the double render and not something designed to actually do something you need (I think?)? To answer that question, we'd need to know what you are trying to achieve. What is your use case? – adsy Jun 23 '23 at 18:42
  • const getAllPokemons = async() => { const pokemonList = await fetchResults( url + `?offset=${offset}&limit=${pageSize}` ); setPokemons((prevPokemons) => [...prevPokemons, ...pokemonList]); }; – Chandra Chud Singh Chundawat Jun 23 '23 at 18:52
  • useEffect(() => { getAllPokemons(); }, [offset]); //offset state updated when scroll reaches bottom of the page to perform infinite scrolling – Chandra Chud Singh Chundawat Jun 23 '23 at 19:02

0 Answers0