When to use onclick ={ myfuntion()} vs onclick={() => (myfunction())} Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of When to use onclick ={ myfuntion()} vs onclick={() => (myfunction())} without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Why is the id undefined in the randomCard function when using the onClick= {(randomCard()} and defined when using onClick = {() => (randomCard())}

function Home() {
    const [cardlist, setCardList] = useState([]);
    const navigate = useNavigate()
    
    function randomCard() {
        const index = Math.floor(Math.random() * cardlist.length);
        const id = cardlist[index].id;
        navigate(`/cards/${id}`)
    }  

    useEffect(() => {
        async function fetchData() {
            const res = await axios.get('https://db.ygoprodeck.com/api/v7/cardinfo.php');
            const results = res.data;
            setCardList(results.data);
            console.log(cardlist);
        }
        fetchData();
    }, [])

    return (
        <div className='home'>
            <h1>Welcome to the Yu-Gi-Oh Database</h1>
            <p>Choose Option</p>
            <div className="options">
                <ul>
                    <li><a href='/allcards'>Show All Cards</a></li>
                    <li><a href='/'>Search Card</a></li>                    
                    <li><a href='' onClick={() => (randomCard())}>Random Card</a></li>                    
                </ul>
               
            </div>
        </div>
  )
}

Answer

One would only use something like

onClick={randomCard()}

when that function returns a function. This situation isn’t uncommon, eg:

const makeHandleClick = (id) => () => {
  setClickedId(id);
};
onclick={makeHandleClick(id))

But it’s a common mistake to use onClick={randomCard()} when you actually only want to run the function when the element is clicked – in which case that will run the function immediately, when rendered, instead of when it’s clicked (and will often result in too many re-renders and an error).

Use

onClick={randomCard}

when you want the function to run when the element is clicked, and not when the element is rendered.

The above is often equivalent to

onClick={() => randomCard()}
We are here to answer your question about When to use onclick ={ myfuntion()} vs onclick={() => (myfunction())} - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji