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

Not rerendering on state change ReactJs

In the arr.js file I have some images. I wrote a function for shuffling the elements in the array. I want react to render the shuffled images when the component is first mounted and also when the images are clicked.

Here is what I tried:

import styled from "styled-components";
import React, {useState, useEffect} from "react";
import Arr from "../utils/arr";

const MainContainer = styled.div`
    display: grid;
    color: white;
    padding: 1rem;
    margin: auto;
    gap: 1rem;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
`

const Main = () => {
    const [arr, setArr] = useState(Arr)

    const shuffleArrayOnClick = (Arr) => {
        for (let i = Arr.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var tmp = Arr[i];
            Arr[i] = Arr[j];
            Arr[j] = tmp;
        }
        return Arr;
    }

    useEffect(() => {
        const shuffle = shuffleArrayOnClick(Arr);
        setArr(shuffle);
    })

    return (
        <MainContainer onClick={shuffleArrayOnClick}>
            {arr}
        </MainContainer>
    )
}

export default Main;

The useEffect runs right after the initial render when no dependency array is set. So I expected the images to be shuffled when the component is first mounted. But the shuffle doesn’t work when I reload the page. Instead the images get shuffled and re-rendered when I change my code and save it.
Also how should I set the onclick function on the array elements?
Thanks in advance.

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

>Solution :

NEVER MODIFY REACT STATE DIRECLY

const shuffleArrayOnClick = (arr) => {
  const Arr = [...arr]
  for (let i = Arr.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var tmp = Arr[i];
      Arr[i] = Arr[j];
      Arr[j] = tmp;
    }
    return Arr;
}

You probably want to run this useEffect once, not million times

useEffect(() => {
  const shuffle = shuffleArrayOnClick(arr);
  setArr(shuffle);
}, [])
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