0

Is it possible to update one state in React and in the same render, can we use the updated value to update another state?

import "./styles.css";
import {useState} from 'react';

export default function App() {
  const [num, setNum] = useState(0)
  const [txt, setTxt] = useState(0)

  handleClick= () =>{
    setNum(num+1)
    setTxt(num+1)
  }

  return (
    <div className="App">
     <input type="submit" value="button" onClick={handleClick} />
     <h1>{num}</h1>
     <h1>{txt}</h1>
    </div>
  );
}

In the above example, both num and txt are initially set to 0. Clicking the button for the first time would increase both num and txt to 1 and it would update both to 2 when clicked again and so on.

Is there way to get the num updated to 1 as soon as setNum(num+1) is called, so that it can update it from 0 to 1 and so while calling setTxt(num+1), it can update it directly to 2?

1 Answers1

1

Yes, you can do that using the useEffect hook with the num as a dependency.

Here's a CodeSandbox:

Edit hungry-montalcini-67kjd

import { useEffect, useState } from "react";

import "./styles.css";

export default function App() {
  const [num, setNum] = useState(0);
  const [txt, setTxt] = useState(0);

  const handleClick = () => {
    setNum(num + 1);
  };

  useEffect(() => {
    if (num > 0) {
      setTxt(num + 1);
    }
  }, [num]);

  return (
    <div className="App">
      <input type="submit" value="button" onClick={handleClick} />
      <h1>{num}</h1>
      <h1>{txt}</h1>
    </div>
  );
}

If the actual state is just a number and not something complex like an array/object then you can simply do this:

const handleClick = () => {
    setNum(num + 1);
    setTxt(num + 2);
  };
Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32
  • 1
    Thank you very much. But there is one problem. Say, if I need to include another button, which on clicking should only update `num` and not `txt`, it would still update txt since `setTxt(num+1)` is called within useEffect. – Gautham Muralidharan Aug 25 '21 at 05:29
  • @GauthamMuralidharan It's better to handle that with two different click handlers instead of using `useEffect`. You can follow the simpler second approach. – Ramesh Reddy Aug 25 '21 at 05:42