2

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 :)

0

1 Answer 1

4

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)) }, []) 
Sign up to request clarification or add additional context in comments.

3 Comments

But i want to re-render useEffect whenever current page is changed. Not every time when pressed back button. Like From "localhost:3000/dashboard" to "localhost:3000" it run useEffect and I don't want that.
If the component is unmounted and remounted then the effect will run. So you need to add some sort of conditional check inside the useEffect to avoid running if the data already exists.
The answer is misleading. It does not run "never again". When the component un-mounts and re-mounts, the effect will be run again even if you pass an empty array. @Octal

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.