Gautham Muralidharan
Gautham Muralidharan

Reputation: 157

simultaneous updates of React in React

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?

Upvotes: 0

Views: 39

Answers (1)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

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);
  };

Upvotes: 1

Related Questions