Raven James
Raven James

Reputation: 21

React state does not re-render

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;

Upvotes: 0

Views: 100

Answers (2)

Piotr Żak
Piotr Żak

Reputation: 2132

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?

Upvotes: 0

Amit Chauhan
Amit Chauhan

Reputation: 6869

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;

Upvotes: 1

Related Questions