0

Help please, I would like to ask why is react state not re-rendering.

the console shows the updated state but not in render.

I have similar code with same scenario, this is just to simplify.

       import React, {useState} from "react";

       const [x, setX] = useState([1]);

       const Sample = () => {
        <div>
            hello
            <button onClick={async () => {
                tempX.push(1);
                console.log(tempX)
                await setX(tempX)

            }}>
              x
            </button>
            {x.map( function(z) {return z})}          
         </div>
       }

       export default Sample;
Community
  • 1
  • 1
Raven James
  • 21
  • 1
  • 2
  • Does this answer your question? [React - will not re render on state change](https://stackoverflow.com/questions/50947867/react-will-not-re-render-on-state-change) – mansour lotfi Jan 14 '20 at 12:03

2 Answers2

1

useState doesn't re-render if last you have setState with same value. You are mutating your array that's why re-render is not happening.

And setState doesn't return promise so you don't need async and await.

Create new copy and then call setX with spread operator.

   import React, {useState} from "react";

   const [x, setX] = useState([1]);

   const Sample = () => {
    <div>
        hello
        <button onClick={() => {
            const updated = [...tempX, 1]; // create new copy of your array;
            console.log(updated)
            setX(updated)

        }}>
          x
        </button>
        {x.map( function(z) {return z})}          
     </div>
   }

   export default Sample;
Amit Chauhan
  • 6,151
  • 2
  • 24
  • 37
0

UseEffect- rerender when second argument (in this case [x] change)

I don't convinced it's what You need:

import React, { useState, useEffect } from "react";


    const Sample = () => {

        const [x, setX] = useState([1]);
        const onClick = (push) => { setX([...x, push]); }

        const itemsToPush = [5, 2, 3, 4]

        useEffect(() => {
            console.log("X changed")
        }, [x])

        return (
            <div>
                hello
            <button onClick={() => onClick(itemsToPush)}>
                    {x}
                </button>
            </div >
        )
    }

    export default Sample;

Hey, any people have idea how to to add array elements(itemsToPush) in the onClick function in sequence?

Piotr Żak
  • 2,046
  • 5
  • 18
  • 30