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

134
Views
What are my options to deal with this stale closure in React besides using ref

I'm using the library React Datasheet Grid, the main component has a property called OnActiveCellChange, to which i'm passing my custom function:

const [selectedCell, setSelectedCell] = useState([])
...
function handleCellSelection({ cell }) { 
   if(cell) {
     const {row, col} = cell;
     const newData = data[row][col]; 

     if(!newData.unpickable) {    
 
       console.log(selectedCell); // prints empty array

       setSelectedCell(selectedCell => [...selectedCell, newData.value]);
     }
   }
 }
...
<DataSheetGrid
   className={'overwriteDisabledStyles'}
   value={data}
   onChange={setData}
   columns={columns}
   onActiveCellChange={handleCellSelection}
   headerRowHeight={false}
   gutterColumn={false}
   lockRows
/>

The problem is that I wish to make some checks with the state variable "selectedCell", while I managed to update the state from with the functional form, I can't access the the state variable. I managed to use the variable using "useRef".

I want to know if I can tackle the problem in any other way.

EDIT:

Trying to clarify my question:

What I want is to, inside the handleCellSelection function, make some checks before inserting the newData using the setSelectedCell. Like searching the selectedCell array for existing values:

const valueAlreadyExists = selectedCell.some((existingCell) => {
   return existingCell === newData.value
});

Yet, when the handleCellSelection function is called, the value of selectedCell is always an empty array. It should be the values that are being inserted in the array. I know there are values there because when I console.log outside the handleCellSelection they appear correctly.

So, I managed to access them inside the handleCellSelection using useRef() but what I am searching for is another option to solve this.

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!