Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
Unable to update React.useState("") after joining all elements in array to single string

I am trying to update a React.useState("") using setDisplay in a function that takes an array of strings and joined them into a single string before setDisplay.

Without the setDisplay, I'm able to console.log() and get the joined array.

const App = () => {
  const [display, setDisplay] = React.useState("");

  const values = [];
  const onClick = (value) => {
    values.push(value);
    console.log(values) // w/o setDisplay output: ["1","2","3","4"]; w/ setDisplay output: ["1"]; ["2"]; ["3"]; ["4"];
    setDisplay(values.join(""))
  };

  return (
    <div className="p-5">
      {display}
      <NumPads data={keypress} onClick={onClick} />
      <OperatorPads data={keypress} onClick={onClick} />
    </div>
  );
};
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

setDisplay((values) => ([...values, value].join("")]))
about 4 years ago · Juan Pablo Isaza Report

0

  const onClick = (value) => setDisplay((dispay) => display.concat('', value));
about 4 years ago · Juan Pablo Isaza Report

0

The reason the console.log seems to work when you don't call setDisplay is simply because the state of the component did not change.

When you call setDisplay, you change the state, so the entire component re-renders, which causes values to reset back to an empty array.

Solution(s)

  • One way to solve this is already shown in a previous answer.

  • Another way is to wrap your values array with useRef:

    const values = useRef([]);
    

    Then access the array using values.current

  • Yet another way is to eliminate the use of values all together and change the callback to:

    const onClick = (value) => {
      setDisplay(display + value);
    };
    
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!