I have hook which fetched the first 10 posts from jsonplaceholder site.
i can see in network tab that fetch req is being called twice.
i have used useEffect, useCallback & useState hook from react
import { useCallback, useEffect, useState } from 'react'
const useAppHook = ({ ref }) => {
const [posts, setPosts] = useState([])
const [start, setStart] = useState(0)
const fetchPosts = useCallback(async () => {
const postFetchUrl = `https://jsonplaceholder.typicode.com/posts?_start=${start}&_limit=10`
const response = await fetch(postFetchUrl)
const postExtracted = await response.json()
if (postExtracted.length) {
setPosts((current) => [...current, ...postExtracted])
}
}, [start])
useEffect(() => {
fetchPosts()
}, [fetchPosts])
const handlePagination = () => {
setStart((current) => current + 10)
}
return {
posts,
handlePagination,
}
}
export default useAppHook
fetch req should happen once
2
Answers
You can try these.
https://upmostly.com/tutorials/why-is-my-useeffect-hook-running-twice-in-react#:~:text=Simply%20remove%20the%20%3CReact.,page%2Dby%2Dpage%20basis.
Check if you have
<StrictMode>
tag as a parent of component that usesuseAppHook
. It enables React’s Strict Mode which helps identify common React pitfalls by mounting/unmounting/remounting components. This happens in development build only and not in production build.