Kisan Kumavat
Kisan Kumavat

Reputation: 97

Why useEffect runs every time when component re-render?

In my Home component(I call it Home Page!) I am using Cards.JS component which has posts attribute as shown in following code.

const Home = () => {
  const dispatch = useDispatch()
  const isLoading = useSelector(state => state.isLoading)
  const currentPage = useSelector((state) => state.idFor.currentPageHome)
  const homePosts = useSelector((state) => state.posts)
  useEffect(() => {
    dispatch(setIsLoading(true))
    dispatch(getAllPosts(currentPage))
  }, [dispatch, currentPage])
  return (
    isLoading ? (
      <Loader type="ThreeDots" color="#000000" height={500} width={80} />
    ) : (
      <Cards posts={homePosts} setCurrentPage={setCurrentPageHome} currentPage={currentPage} pageName={"LATEST"} />
    )
  )
}

And Cards.Js is as following

const Cards = ({ posts, setCurrentPage, currentPage, pageName }) => {

  console.log('Cards.JS called', posts);
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(setIsLoading(false))
  })

  const handleNextPage = () => {
    dispatch(setIsLoading(true))
    dispatch(setCurrentPage(currentPage + 1))
  }
  const handlePreviousPage = () => {
    dispatch(setIsLoading(true))
    dispatch(setCurrentPage(currentPage - 1))
  }

  return (
    <div className="container">
      <h4 className="page-heading">{pageName}</h4>
      <div className="card-container">
        {
          posts.map(post => <Card key={post._id} post={post} />)
        }
      </div>
      <div className="page-div">
        {currentPage !== 1 ? <span className="previous-page" onClick={handlePreviousPage}>&lt;</span>
          : null}
        <span className="next-page" onClick={handleNextPage}>&gt;</span>
      </div>
    </div>
  )
}

My Problem: When i come back to home page useEffect is called everytime and request same data to back-end which are already avaliable in Redux store.

Thanks in Advance :)

Upvotes: 2

Views: 10319

Answers (1)

Octal
Octal

Reputation: 197

useEffect will run every time the component rerenders.

However, useEffect also takes a second parameter: an array of variables to monitor. And it will only run the callback if any variable changes in that array.

If you pass an empty array, it will only run once initially, and never again no matter how many times your component rerenders.

useEffect(() => {
  dispatch(setIsLoading(false))
}, [])

Upvotes: 4

Related Questions