Home > OS >  ui is not updating even though useState is changing
ui is not updating even though useState is changing

Time:05-25

import React, { useEffect, useState } from "react";
import "./App.css";

function App() {
const [data, setData] = useState({ count: 1 });

const handleClick = () => {
let temp = data;
data.count  = 1;

console.log("temp: ", temp);  // temp: {count: 2}

setData(temp);
console.log(data); //{count: 2}
};

React.useEffect(() => {
console.log("hello");
}, [data]);

 return (
<div className="App">
  {data.count}

   <button onClick={handleClick}>add</button>
 </div>
 );
 }

 export default App;

the state is changing but in the UI display data is not updating. i don't know why? like if I click on the add button the state is changing from

data = {count: 1} to data = {count: 2}

but in the ui display the data remain 1. it is not updating in the ui. so what to do?

CodePudding user response:

In the handleClick method, you are trying to directly mutate the state by incrementing data.count by 1; but we should never mutate the state directly. React compares the previous state with the updated state to decide if the component needs re-rendering; so, if we modify state directly, it will disturb this process. As a result, the component will behave unexpectedly.

Try setting the state like this:

const handleClick = () => {
   setData((prevCount) => ({
     count:prevCount.count   1
}))};

CodePudding user response:

You can update object state like this.


import React, { useEffect, useState } from 'react';

function App() {
  const [data, setData] = useState({ count: 1 });

  const handleClick = () => {
    let temp = data;
    temp.count  = 1;
    console.log('temp: ', temp); // temp: {count: 2}
    setData({...temp});
  };

  React.useEffect(() => {
    console.log('hello');
  }, [data]);

  return (
    <div className="App">
      {data.count}

      <button onClick={handleClick}>add</button>
    </div>
  );
}

export default App;

And this is more readable.

import React, { useEffect, useState } from 'react';

function App() {
  const [data, setData] = useState({ count: 1 });

  const handleClick = () => {
    setData({ ...data, count: data.count   1 });
  };

  React.useEffect(() => {
    console.log('hello');
  }, [data]);

  return (
    <div className="App">
      {data.count}

      <button onClick={handleClick}>add</button>
    </div>
  );
}

export default App;

  • Related