React: Dont's in Hooks

useEffect() 

1. When the value of a variable is already derived from an existing state.
💡: React anyway renders the component again with the latest state value. No need to again watch for changes in useEffect()
Use case: Call an API when the count value changes

export default function UseEffectDemo() {
    const [count, setCount] = useState(0);
    const handleClick = () => {
        setCount(count+1)
    }
    const callAPI = () => {
        return `/api/data/${count}` <--- NO need to do useEffect(() => {}, [count])
    }
    return (
        <>
            {count}
            <button onClick={handleClick}>increment</button>
            <p>Calling API {callAPI()}</p> <--- Calling API 1, Calling API 2....
        </>
    )
}


2. Try not to have an object in useEffect() dependency array to avoid unnecessary re-rendering

💡: JS compares objects by reference and not by values inside the objects
So { foo: "bar" } === { foo: "bar" } //false since they have different references

import { useState,useEffect } from "react"

export default function UseEffectDemo() {
    const [name, setName] = useState({foo: "bar"});
    const [api, setAPI] = useState(0);
    const handleClick = () => {
        setName({foo: "bar"})
    }
    useEffect(() => {
        console.log(`I will keep running at every render since name is always
set to a new object with same value {foo: 'bar'} every time which gets a new refence`)
        setAPI(`/api/data/${name.foo}`)
    }, [name])
    return (
        <>
            <button onClick={handleClick}>increment</button>
            <p>Calling API {api}</p>
        </>
    )
}

Fix:

    useEffect(() => {
        console.log("I will run only when the foo value changes")
        setAPI(`/api/data/${name.foo}`)
    }, [name.foo]) <--- using a particular value in the object of primitive type


3. Cleanup
💡: a return function can be written at the end of useEffect() that runs every time its dependency changes or when the component is unmounted

Make sure you run clearTimeout() or clearInterval() at the end.


4. Fetching API
useEffect() is not the right place to write API fetch.

2 options:
a) use Next.js and typically written in server components
b) use WSR library if you want client components only. This already does some smart fetching like caching outputs if same request made again etc













































































Comments