skip to Main Content

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


  1. You can try these.

    1. Use useRef to keep track of fetching data with start, if you fetched data with start, you don’t call it again.
    2. Disable React Strict Mode

    https://upmostly.com/tutorials/why-is-my-useeffect-hook-running-twice-in-react#:~:text=Simply%20remove%20the%20%3CReact.,page%2Dby%2Dpage%20basis.

    Login or Signup to reply.
  2. Check if you have <StrictMode> tag as a parent of component that uses useAppHook. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search