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

181
Views
I'm using useState to change the state of an element based on if a checkbox if checked or not, but the state is not updating - couldnt find reason
import { useCallback, useEffect, useState, useRef } from 'react';

const [changeEl, setChangeEl] = useState(false);
let chosenInput = useRef();
let result = useRef();
let allCheckboxes = [];

 const checkHandler = useCallback(
    async (e) => {
      const allInputs = document.querySelectorAll('input');
      for (const input of allInputs) {
        if (input.type === 'checkbox') {
          allCheckboxes.push(input);
        }
      }
      chosenInput.current = e.target;
      if (chosenInput.current.name === 'notChecked') {
        chosenInput.current.name = 'checked';
      } else {
        chosenInput.current.name = 'notChecked';
      }

      for (const [i, value] of result.current.entries()) {
        if (
          chosenInput.current.name === 'checked'
        ) {
          allCheckboxes[i].disabled = true;
          console.log(allCheckboxes[i].disabled) //TRUE
          chosenInput.current.disabled = false;
          setChangeEl(allCheckboxes[i].disabled); 
          console.log(ChangeEl) //THIS IS STILL FALSE BUT IT IS SUPPOSED TO CHANGE

        }
        if (chosenInput.current.name !== 'checked') {
          allCheckboxes[i].disabled = false;
          setChangeEl(allCheckboxes[i].disabled); 
          console.log(changeEl) //THIS WORKS
        }
      }
    },
    [changeEl, allCheckboxes]
  );

the changeEl is false even when I'm setting it to true. But it is false when I'm setting it to false. I think it has something to do with the useState not updating it immediately but I'm not sure it's updating it at all. If I'm using useContext to update it it works but I don't want to do that because it is unnecessary. I couldn't find an answer for this so I would really appreciate the help.

about 4 years ago · Santiago Gelvez
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!