Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReactJS parent child ref has outdated child state

I’m using useRef() to call a childs function from my parent component. The issue is the childs state (betHistory) is empty whenever the parent calls the childs undo function, but when undo() is called by the child itself, the state is in date (filled with all the values that have been pushed to it). Why is my parent seeing an empty version of betHistory when calling undo() vs when undo() is called by the child itself?

Parent

import './App.css';
import Table from './Table';
import React, { useEffect, useState, useRef } from 'react';

function App() {
  const table = useRef();

  function undo() {
    table.current.undo();
  }

  return (
    <div className="App">
      <div className="table-section">
        <Table ref={table}></Table>
      </div>
      <div className="button" onClick={undo}>Click me</div>
    </div>
  );
}

export default App;

Child

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React, { useState, forwardRef, useImperativeHandle } from 'react';
import './Table.css';

function Table(props, ref) {

  const [betHistory, setBetHistory] = useState([]);
  const [betCount, setBetCount] = useState(0);


  function placeBet(element) {
    const newBetHistory = [...betHistory, betCount.toString()];
    setBetHistory(newBetHistory);
    setBetCount((1 + betCount));
  }

  function undo() {
    console.log(betHistory);
  }

  useImperativeHandle(ref, () => ({
    undo() {
      undo();
    }
  }), [])

  return (
    <div className="button" onClick={undo}>Click me</div>
    <div className="bet-button" onClick={placeBet}></div>
  );
}

export default forwardRef(Table)

>Solution :

  useImperativeHandle(ref, () => ({
    undo() {
      undo();
    }
  }), []) // ---> Try remove this []

It has to do with the empty array you specified. Try removing it. Just like in useEffect when you specify empty array as dependency it will run only once, so the function captured inside is from first render, hence you don’t see recent data.

Or you can specify correct dependencies.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading