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

My React app gets rerendered more than one time after a click event occurs even after using useEffect()

I am trying to call this endpoint to generate random memes when a a user clicks on a button. I am using the fetch api inside the useEffect hook,and the button works fine, but when I click it, there is splash of a new image for a split second and then the image disappears as the app gets re-rendered. I do not know why this is happening.

Here is my code:

import {useState, useEffect, useCallback} from 'react';

const Ui = () => {

// updating the state

const [url, setUrl ] = useState({})
const [meme, setMeme ] = useState([])




useEffect(()=>{
   fetch('https://api.imgflip.com/get_memes')
    .then(res => res.json())
    .then(data=> setMeme(data.data.memes))

}, [])



// function that brings a random image

const getAMeme = ()=>{
    const randomNum = Math.floor(Math.random() * meme.length)
    const url = meme[randomNum].url
    console.log(url)
    setUrl(prevUrl =>({
        ...prevUrl, 
        randomImage: url
    }))
   
}



    return (
        <div className = "ui">

                {/* form */}

                <form>

                    <input placeholder="Enter first sentence"></input>
                    <input placeholder="Enter second sentence"></input>
                    <button onClick={getAMeme}>Generate Meme</button>
            
                </form>                

                {/* meme image */}
                <div className="image">
                    <img src={url.randomImage} alt="cool" />
                </div>
            
        </div>
    );
}

export default Ui;

I am calling the endpoint inside the useEffect but it seems like the app gets rerendered multiple times.

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 :

Having a form will make your page reload. By removing it you can make it work.
If you still need to have the form and do the things you can try like this.

    <form onSubmit={(e)=>e.preventDefault()}>
           // ..... form content inside ...
   </form>    
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