Search code examples
javascriptreactjsuse-effect

How can I delay useEffect Hook


I am using 2 useEffects on a file and the second useEffect is dependent on the first one.

Is there a way of delaying the second useEffect until the data from the first useEffect has been gotten?

const params = useParams()
const [userData, setUserData] = useState({})
const [followers, setFollowers] = useState([])

useEffect(() => getUser(params.id), [])

useEffect(() => {
    getFollowers(userData?.user?._id, auth.token)
}, [])

const getUser = async (id) => {
    const res = await getUserProfile(id)

    if (res) {
      setUserData(res)
    }
}


const getFollowers = async (id, token) => {
    const res = await getUserFollowers(id, token)
    if (res) {
      setFollowers(res)
    }
}

Solution

  • Execute second useEffect only if first useEffect has retrieved its data:

    const params = useParams()
    const [userData, setUserData] = useState(null) // initialize userData as null
    const [followers, setFollowers] = useState([])
    
    useEffect(() => getUser(params.id), [])
    
    useEffect(() => {
        // wait until userData is defined to make the second call
        if (userData)
            getFollowers(userData?.user?._id, auth.token)
    }, [userData])