How to use the return value from React hook updater function?

I’m using the following code as an updater function for my state (inside hook).

While the console output works properly inside the callback, how can I access the value outside. I am returning someStatus and assign it to x. But x is printed as undefined.

Is there some issue with the code below?

let x = setSomeStatus((someStatus) => {
    console.log("Some Status :::: :" + someStatus); // "XYZ"
    return someStatus;
});
console.log("x = " + x); // undefined

I tried below as suggested, but still do not get updated value outside the callback;

setSomeStatus((someStatus) => {
    console.log("File Status :::: :" + someStatus); // "XYZ"
    return someStatus;
});
console.log("someStatus = " + someStatus);

BELOW SEEMS TO BE WORKING (Please confirm if it looks good)

const onCellClicked = (e) => {
        if (e.data.status !== 'TO') {
            console.log(e);
            //let fileStatus;
            let fileType = (e.data.status === 'Y') ? 'O' : 'I';
            setCurrentFileStatus(e.data.status);
            setFileType(fileType);

            var tempObj = {};
            setCurrentFileStatus((fileStatus) => {
                setFileType((fileType) => {
                    tempObj.currentFileStatus = fileStatus;
                    tempObj.summaryDate = form.dateField;
                    tempObj.fileType = fileType;
                });             
            });
            setSharedData(tempObj);
            console.log("tempObj = " + tempObj);
        }
    }

Assuming that setSomeStatus is a setState function, the return statement of the callback you pass to setState will just return from the callback, and consequently set the state, but not actually return a value from the setState function.

As you anyways already have a state defined, you don’t need to store it in a separate variable (x in your case), you can access it directly.

const { useState } = React;

const App = () => {
  const [someState, setSomeState] = useState();

  return (
    <div>
      <p>Type something to change the state</p>
      <input
        onInput={(e) =>
          setSomeState((prev) => {
            console.log("changing the state from", prev, "to", e.target.value);
            return e.target.value;
          })
        }
      />
      <h2>The state is {someState}</h2>
    </div>
  );
};

// Render it
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Leave a Comment