Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
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, i.e. 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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!