Search code examples
javascriptreactjsreduxuse-effect

Why Home.js and Cards.js are called many time?


Here is my Console with console logged values.

Console Screenshot

Home Page is called 4 times i dont know why and Cards.js is also called even if i am checking for loading.

Here is my Home.js Code. I have tried removing dependency from effect hook but didn't worked.

const Home = () => {

  console.log('Home Page');

  const dispatch = useDispatch()
  const loading = useSelector(state => state.idFor.loading)
  const currentPage = useSelector((state) => state.idFor.currentPageHome)
  const homePosts = useSelector((state) => state.posts)

  useEffect(() => {
    console.log('Home effect');
    dispatch(setLoading(true))
    dispatch(getAllPosts(currentPage))
  }, [dispatch, currentPage])

  return (
    loading ? (
      <Loader type="ThreeDots" color="#000000" height={500} width={80} />
    ) : (
      <Cards posts={homePosts} setCurrentPage={setCurrentPageHome} currentPage={currentPage} pageName={"LATEST"} />
    )
  )
}

Here is my Cards.js code

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

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

  if (posts.length !== 0) {
    dispatch(setLoading(false))
  }

  const handleNextPage = () => {
    dispatch(setLoading(true))
    dispatch(setCurrentPage(currentPage + 1))
  }
  const handlePreviousPage = () => {
    dispatch(setLoading(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>
  )
}

Solution

  • The problem is from redux state.

      const loading = useSelector(state => state.idFor.loading)
      const currentPage = useSelector((state) => state.idFor.currentPageHome)
      const homePosts = useSelector((state) => state.posts)
    

    When the redux state is updated, the Home component is called.

    The each component is synced with redux state.

    enter image description here

    1. first loading
    2. useEffect worked (home component, currentPage from redux)
    3. loading updated (redux state)
    4. data updated (redux state)

    Thank you.

    contact me here if you want learn more