简体   繁体   中英

Prevent loading components with default values in React useState

I am working with offset pagination in typescript react.

I have two states that contain pageNumber and offset . The default page is set to 1 and the default offset is set to 0 as you can see below.

useState Hook

  const [currentPage, setCurrentPage] = useState(1);
  const [calculatedOffset, setCalculatedOffset] = useState(0);

On load, the component fetches pageNumber and calculatedOffset from the localStorage and updates the defaults of the useState values.

useEffect Hook

  useEffect(() => {
    if (typeof window !== "undefined") {
      const integerPage = parseInt(localStorage.getItem("currentPage") || "1");
      setCurrentPage(integerPage);

      const integerOffset = parseInt(localStorage.getItem("calculatedOffset") || "0");
      setCalculatedOffset(integerOffset);
    }
  }, []);

THE PROBLEM:

The problem I am facing is that whenever the component loads, it loads up with the values of the default state, ie pageNumber: 1, calculatedOffset: 0 for half a second then changes it to the updated state that was which was updated when the useEffect hook ran. So on every load, the component flashes the data of the default state before ending up from the updated state fetched from localStorage.

Is there a way I can make it where the component only loads when the states have ended up on their final values and prevent the old states flashing for half a second behaviour every time the component loads?

useEffect runs when the component has been rendered fully. So before that happens, useState is already used to initialise the variables according to which your components are initially rendered.

To prevent the initial render according to the initialised value from useState , set both to null in useState and in the component, render the elements conditionally:

{!currentPage || element}

or

{currentPage && element}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM