Search code examples
reactjsreact-hooksuse-effectuse-state

Photos reload when useEffect is called in React


I have 5 photos(gifs) taken from database randomly. I have state pressedGif which defines index of photo clicked. I want to add onclick event to each of them (in a for loop):

export default function GameObject(props) {
  const addedToGameGif = [];
  const PhotoCards = [];

  const [pressedGif, gifPressed] = useState(-1);

  useEffect(() => {
    console.log('HELLO');
  }, []);

  // get random photos to addedToGameGif array
  // ...

  for (let i = 0; i < addedToGameGif.length; i += 1) {
     PhotoCards.push(
      <div>
        <Card
          id={i}
          onClick={() => gifPressed(i)}>
          <img src={addedToGameGif[i]} />
        </Card>
      </div>,
    );
  }
  return <div>{PhotoCards}</div>;
 }

I get HELLO message in console successfully, but problem is that my randomly picked photos also changes to different ones. So how do I prevent that photo reloading and calling of function which picks photos randomly?


Solution

  • I would recommend something like this:

    import React from 'react';
    
    const PhotoCard = props => {
      const [addedToGameGif, setAddedToGameGif] = React.useState([]);
      const [pressedGif, setPressedGif] = React.useState(-1);
      // set random pictures
      React.useEffect(() => {
        const setRandomGifs = () => {
          let randomGifs = [];
          // make request to get random gifs
          // some loop () {
          // randomGifs.push(randomGif);
          // }
          setAddedToGameGif(randomGifs);
        };
        setRandomGifs();
      }, []);
      return (
        <>
          {addedToGameGif.map((gif, index) => {
            return (
              <Card
                id={index}
                onClick={() => setPressedGif(index)}
                key={'photo-card-' + index}
              >
                <img src={gif[index]} alt={'card-img' + index} />
              </Card>
            );
          })}
        </>
      );
    };
    
    export default PhotoCard;
    

    If that doesn't work, check if your component gets his props changed too often from a parent, so the useEffect-Hook gets called every time that happens.