'Why my state always is default value when call inside Callback?

I don't know exactly what is my problem. I used some library. When i use callback and trying to get state of Component, the state always is default value.

Example when i use mui-datatables https://github.com/gregnb/mui-datatables

import React, { useState } from 'react'
import MUIDataTable from "mui-datatables";

const columns = [
    {
        name: "name",
        label: "Name",
    },
    {
        name: "company",
        label: "Company",
    },
    {
        name: "city",
        label: "City",
    },
    {
        name: "state",
        label: "State",
    },
];

const data = [
    { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
    { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
    { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
    { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" },
];


const MyComponent = () => {

    const [myState, setMyState] = useState("default value");
    const onRowClick = (rowData, rowMeta) => {
        console.log(myState) //always default value
    }

    const options = {
        onRowClick: onRowClick 
    }
    return (
        <div>
            <MUIDataTable
                title={"Employee List"}
                data={data}
                columns={columns}
                options={options}
            />

            <button onClick={ () => setMyState("State changed")}>Change state</button>
            <p>{myState}</p>

        </div>
    )
}

First, I click button to change MyState, the state changed in p tag. Next, I click any row to console MyState. But, it's always is default value. Why? Code in CodeSanBox: https://codesandbox.io/s/dreamy-germain-tuylh



Solution 1:[1]

I have converted your component to a class, and now it's working as you wanted. You can see below the error that was happening when you were trying to use a functional component. This is probably due to how mui-datatables is built. It probably requires a class component to work.

Working example on CodeSandbox

import React from "react";
import ReactDOM from "react-dom";

import MUIDataTable from "mui-datatables";

const columns = [
  {
    name: "name",
    label: "Name"
  },
  {
    name: "company",
    label: "Company"
  },
  {
    name: "city",
    label: "City"
  },
  {
    name: "state",
    label: "State"
  }
];

const data = [
  { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
  { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
  { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
  { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" }
];

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      myState: "default value"
    };
    this.options = { onRowClick: this.onRowClick };
    this.onRowClick = this.onRowClick.bind(this);
  }

  onRowClick(rowData, rowMeta) {
    console.log(this.state.myState); //always default value
  }

  render() {
    return (
      <div>
        <MUIDataTable
          title={"Employee List"}
          data={data}
          columns={columns}
          options={{ onRowClick: this.onRowClick }}
        />

        <button onClick={() => this.setState({ myState: "State changed" })}>
          Change state
        </button>
        <p>{this.state.myState}</p>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyComponent />, rootElement);

With your code, I was get the following error:

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `WithStyles(Tooltip)`.
    in Tooltip (created by WithStyles(Tooltip))
    in WithStyles(Tooltip) (created by t)
    in t (created by l)
    in span (created by l)
    in div (created by l)
    in div (created by ForwardRef(Toolbar))
    in ForwardRef(Toolbar) (created by WithStyles(ForwardRef(Toolbar)))
    in WithStyles(ForwardRef(Toolbar)) (created by l)
    in l (created by t)
    in t (created by WithStyles(t))
    in WithStyles(t) (created by t)
    in t (created by t)
    in div (created by ForwardRef(Paper))
    in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
    in WithStyles(ForwardRef(Paper)) (created by t)
    in t (created by WithStyles(t))
    in WithStyles(t) (created by MyComponent)
    in div (created by MyComponent)
    in MyComponent

Solution 2:[2]

It's something with mui-table. Looks like it does not handle if options.rowClickis changed. I've put breakpoint into MUIDataTable.render() and it's called just once. Providing different options does not re-render that.

So if I add key like

<MUIDataTable
  key={myState}
  ...

to force it be re-created instead of updating - it works and State changed is displayed in console.

But maybe it'd be better to file issue in their github. Or try most recent version.

Solution 3:[3]

I was able to solve a similar problem by utilizing the useRef hook. Reference this answer for more information.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 skyboyer
Solution 3 Bernard