Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
Get value returned by useState

Get value returned by useState when state updates first time.

In following code : Initial value is 0 and after clicking on button value will be 1.I want to store value1 in firstValue and value2 in secondValue and these values must be immutable.

function App() {
  const [count, setCount] = React.useState(0);  
// const firstValue = 
// const secondValue =

  return <button onClick={() => setCount(count+1)}> value {count}</button>;
}

ReactDOM.render(<App count={0}/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js" integrity="sha256-3vo65ZXn5pfsCfGM5H55X+SmwJHBlyNHPwRmWAPgJnM=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js" integrity="sha256-qVsF1ftL3vUq8RFOLwPnKimXOLo72xguDliIxeffHRc=" crossorigin="anonymous"></script>

<div id='root'></div>

Value will be stored only first and second click of button and these values must be immutable.

Expected Output

firstValue = value1
secondValue = value2
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Perhaps another state variable can be responsible for this part?

const MAX = 2
function App() {
  const [count, setCount] = React.useState(0);
  const [values, setValues] = React.useState([]);
  function onClick () {
    if (count < MAX) {
      setValues([...values, count])
    }
    setCount(count+1)
  }
  
  const [firstValue, secondValue] = values

  return (
    <div>
      <button onClick={onClick}> value {count}</button>
      <p>first value: {firstValue}</p>
      <p>second value: {secondValue}</p>
    </div>
  )
}

ReactDOM.render(<App count={0}/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js" integrity="sha256-3vo65ZXn5pfsCfGM5H55X+SmwJHBlyNHPwRmWAPgJnM=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js" integrity="sha256-qVsF1ftL3vUq8RFOLwPnKimXOLo72xguDliIxeffHRc=" crossorigin="anonymous"></script>

<div id='root'></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Assuming value1 is count's previous state, and value2 is count's current state.

function App() {
  const [count, setCount] = React.useState(0);
  //Initialize the variables
  let firstValue = count;
  let secondValue = count;

  return (
    <button
      onClick={() => {
        firstValue = secondValue; // set first value equal to previous count value
        secondValue = count + 1; // set second value equal to new count value
        setCount(count + 1); // update the state
      }}
    >
      value {count}
    </button>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

  • Not sure this is optimal solution, but a way using useRef
  • gather's all the values not only first two, but yes key names can be altered as per your convenience

    function App() {
      const [count, setCount] = React.useState(0);  
      const values = React.useRef({});
  
      const updateValue = () => {
        setCount(count+1);
        // get previous values using spread, and then add the dynamic using square brackets
        values.current = {...values.current, ["value" + (count+1)]: count+1 }
      }
      // you may require this values.current
      console.log(values.current)
      return <button onClick={() => updateValue() }> value {count}</button>;
    }

    ReactDOM.render(<App count={0}/>, document.getElementById('root'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js" integrity="sha256-3vo65ZXn5pfsCfGM5H55X+SmwJHBlyNHPwRmWAPgJnM=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js" integrity="sha256-qVsF1ftL3vUq8RFOLwPnKimXOLo72xguDliIxeffHRc=" crossorigin="anonymous"></script>

    <div id='root'></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda