Home > database >  react.js not refreshing state update with date value
react.js not refreshing state update with date value

Time:03-17

This is a simple react code,

import { useState } from "react";
export default function App() {
  const [dateValue, setDateValue] = useState(new Date());
  const dateUpdate = () => {
    const newDate = dateValue;
    newDate.setMonth(dateValue.getMonth()   1);
    console.log(newDate);
    setDateValue(newDate);
  };
  return (
    <>
      <div className="App">{dateValue.getMonth()}</div>
      <div>
        {" "}
        <button
          onClick={(e) => {
            dateUpdate();
          }}
        >
          Click
        </button>
      </div>
    </>
  );
}

However, the date value changes show updated values in the console output, but are not reflected in the view, the output remains the same.

If we simply add another state value, it redraws the view, but why don't it with the date field alone? wondering the theory behind it.

CodePudding user response:

React re-uses the previous render output, for performance reasons, because the references to all previous states are unchanged.

When you call setDateValue(newDate) you are not actually updating state from the perspective of React, because newDate and dateValue are the exact same reference.

In order to inform React that there is new state, you need to update state with a new reference with something like const newDate = new Date(dateValue); instead.

CodePudding user response:

There is a minor mistake in your code:

Instead of this: const newDate = dateValue; Do this: const newDate = new Date(dateValue);

The reason: You need to tell react that there is an update by wrapping it in new Date() since dateValue and newDate will reference to same.

Here is the full code mate:

import { useState } from "react";
export default function App() {
  const [dateValue, setDateValue] = useState(new Date());
  const dateUpdate = () => {
    const newDate = new Date(dateValue);
    newDate.setMonth(dateValue.getMonth()   1);
    console.log(newDate);
    setDateValue(newDate);
  };
  return (
    <>
      <div className="App">{dateValue.getMonth()}</div>
      <div>
        {" "}
        <button
          onClick={(e) => {
            dateUpdate();
          }}
        >
          Click
        </button>
      </div>
    </>
  );
}

  • Related