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

88
Views
React State variable keeps resetting and changing within one render

export default function Questionnaire(props) {
    const initialState = {
        questionCount: 0,
        is_host: false
    }
    const [ roomData, setRoomData ] = useState(initialState) 
    const { roomCode } = useParams()
    const [ displayedTable, setDisplayedTable ] = useState(1);

    useEffect(() => {
        fetch("/audio/get-room" + "?code=" + roomCode)
          .then(res => res.json())
          .then(data => {
            setRoomData({
              roomData,
              questionCount: data.questionCount,
              is_host: data.is_host,
            })
          })

          window.addEventListener('keydown', (e) => {
            console.log("questionCount 1:", roomData.questionCount);
            if (e.keyCode == '39') {
                setDisplayedTable(showNextStage(displayedTable, roomData.questionCount));
            } else if (e.keyCode == '37') {
                setDisplayedTable(showPreviousStage(displayedTable));
            }
        });

        // cleanup this component
        return () => {
          window.removeEventListener('keydown', (e) => {
            if (e.keyCode == '39') {
                setDisplayedTable(showNextStage(displayedTable, roomData.questionCount));
            } else if (e.keyCode == '37') {
                setDisplayedTable(showPreviousStage(displayedTable));
            }
        });
        };
    },[roomCode,setRoomData])

    console.log("questionCount 2:", roomData.questionCount);

    return (
        <div>
            {components[displayedTable]}
        </div>
    )
  }

Every time the State refreshes, the two console.logs() return "questionCount 1: 0" and "questionCount 2: 5" (the value fetch() retrieves). But since questionCount is only set to 0 in the initial UseState(), it shouldn't be resetting to 0 and should remain at 5 after it gets set to that. But it doesn't. Why is this? How is it even possible for the one State variable to have two different values in the one render(), when State changes are meant to rerender the page?

about 4 years ago · Juan Pablo Isaza
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!