bassman21
bassman21

Reputation: 390

How to solve issue with React updating state (using useState / setState) properly but no rerendering component?

The following code demonstrates an issue with React that I cannot solve.

Clicking the button "Update State" triggers an update of state by replacing the current state (array with 3 strings) by an updated array (with 4 strings).

strings as well as state are updated properly as the console.logs show. However, the React component is not rerendered (the 4th paragraph with "String D" is not shown). What can I do to ensure that the rerendering takes place immediately after updating the component's state with setState? I thought that using the setState function of the useState hook should always trigger the rerendering process.

const { useState } = require('react');

let strings = [
  "String A",
  "String B",
  "String C"
]

const TestComponent = () => {
  const [ state, setState] = useState(strings);

  const click = () => {
    strings.push("String D");
    console.log(strings);
    setState(strings, console.log(state));
  }
  
  return (
    <div>
      { state.map( (item) => <p>{item}</p>) }
      <button onClick={click}>Update State</button>
    </div>
  )
};

export default TestComponent;

Upvotes: 0

Views: 43

Answers (2)

Sofiane
Sofiane

Reputation: 95

Try this

const click = () => {
setState([...strings, "String D"]);
  }

Upvotes: 1

Mario Vernari
Mario Vernari

Reputation: 7306

React is about immutability, so you have to avoid to mutate the array, but replace it entirely:

  const click = () => {
    const copy = [...strings]; //create a copy
    copy.push("String D");
    console.log(copy);
    setState(copy, console.log(state));
  }

An alternative syntax is this:

  const click = () => {
    const copy = [...strings, "String D"];
    console.log(copy);
    setState(copy, console.log(state));
  }

Upvotes: 1

Related Questions