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([])

    .then(res => res.json())
    .then(data=> setMeme(

}, [])

// function that brings a random image

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

    return (
        <div className = "ui">

                {/* form */}


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

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

export default Ui;

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

>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 ...

Leave a Reply