0

When I run this component, both effects are being called. How to prevent the second one from being called on component mount?

const Item = ({route, navigation, ...props}) => {
    const [page, setPage] = useState(0)

    useEffect(() => {
      console.log('component mount')
      //call API with page 0
      //call another API
    }, [])

    useEffect(() => {
      console.log('called', page)
      //call API with page {page}
    }, [page])

    
    console.log('render')
    return (
        <Text>test</Text>
    );
}
Malik M
  • 101
  • 1
  • 9
Edison Biba
  • 4,384
  • 3
  • 17
  • 33
  • 1
    yes it should run only if "page" is changed, but on initial rendering it will be fired as well, cause basically it is changed - from "nothing" to 0 in your case – Nikita Chayka Dec 15 '20 at 17:11
  • Does this answer your question? [React Hooks - useEffect fires even though the state did not change](https://stackoverflow.com/questions/54923896/react-hooks-useeffect-fires-even-though-the-state-did-not-change) – JBallin Dec 15 '20 at 17:12
  • @NikitaChayka I understand it but how to make it not run at the first time because I can't even make if conditions there – Edison Biba Dec 15 '20 at 17:14
  • @JBallin it explains why it happens but it doesn't give any workaround to that – Edison Biba Dec 15 '20 at 17:15
  • You can use the condition for that in 2nd useEffect – Nilesh Kant Dec 15 '20 at 17:18
  • What do you mean under "i can't even make if"? Your only option would be to have some "if" condition inside second hook. You can check ideas here - https://stackoverflow.com/questions/53253940/make-react-useeffect-hook-not-run-on-initial-render – Nikita Chayka Dec 15 '20 at 17:19
  • I can't use any condition there. If I check to make the API call when page is not 0 then what when user goes from page 1 to page 0? – Edison Biba Dec 15 '20 at 17:19
  • @NikitaChayka I can make an if condition there but like I explained in my previous comment that doesn't work in my case for pagination – Edison Biba Dec 15 '20 at 17:20
  • @EdisonBiba check this link - https://stackoverflow.com/questions/53253940/make-react-useeffect-hook-not-run-on-initial-render The best answer there is to useRef to handle this – Nikita Chayka Dec 15 '20 at 17:22
  • Please refer this for workaround https://stackoverflow.com/questions/53253940/make-react-useeffect-hook-not-run-on-initial-render – Nilesh Kant Dec 15 '20 at 17:24

1 Answers1

1

useEffect will always run on the initial render, but you can use conditions to determine what actions should be taken within the effect.

In your case no conditions are needed, you just need to remove API call for page 0 in your first effect - so that it gets called in your 2nd.

JBallin
  • 8,481
  • 4
  • 46
  • 51