Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recurring function with useState – React

I have read up on hashing iteration and although this is not a question about security I can´t seem to find information on how to actually do this correct.

I thought that when in React, this should be done with useState, but im clearly missing something here.

Full code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { sha256 } from "js-sha256";
import { useState } from "react";

function App() {
  const [currentHash, setCurrentHash] = useState("summer1");

  function iterate(iterations) {
    for (let x = 0; x < iterations; x++) {
      setCurrentHash(sha256(currentHash)); //Does 1 hash only
      console.log("Hashed", x, "times"); //Logs 4 times
    }
  }

  return (
    <div className="App">
     
        <button onClick={() => iterate(4)}> Klick</button>
        currentHash: {currentHash}
        {/* Correct hashes */}
        <p>0: summer1</p>
        <p>1: {sha256("summer1")}</p>
        <p>2: {sha256(sha256("summer1"))}</p>
        <p>3: {sha256(sha256(sha256("summer1")))}</p>
        <p>4: {sha256(sha256(sha256(sha256("summer1"))))}</p>
 
    </div>
  );
}

export default App;

>Solution :

sha256(currentHash) is going to give you the same result no matter how many times you run it.

currentHash won’t be updated until the component is re-rendered and a new value is pulled out of the state and assigned to the new instance of currentHash at the top of the function.

You need to:

  1. store the result in a variable — not the state
  2. use the value of that variable as the input to the function
  3. store the final result in the state at the end
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading