1

I'm having a problem with the useEffect() and dispatch() action. I'm using the latest version of react "^18.1.0". Basically, I have the following code that is defined inside a simple.

const Item = () => {

    const dispatch = useDispatch()
    const user = useSelector(state => state.authReducer.user)

    useEffect(() => {
        dispatch(fetchItems()).then(res => console.log(res)).catch(err => console.log(err))
    }, [dispatch])

    return (
        <div id='data-container'>
            <Navbar />
            <div id='data-wrap'>
                Data
            </div>
        </div>
    );
}

export default Item 

The fetchItems() is a simple function that gets some data from API.

The problem is that the action is dispatched two times but instead I would like that the action is dispatched only one time.

Any help guys will be appreciated.

Thanks.

Yasin Br
  • 1,675
  • 1
  • 6
  • 16
LucaT
  • 333
  • 5
  • 13
  • 2
    Does this answer your question? [React 18, useEffect is getting called two times on mount](https://stackoverflow.com/questions/72238175/react-18-useeffect-is-getting-called-two-times-on-mount) – Youssouf Oumar May 19 '22 at 08:48

2 Answers2

6

it's normal when you are running React in development mode. (it's React checking that everything is working fine).

Try building a production build and it should behave normally.

Also it's correct to have dispatch in the dependency array because it's never changing its reference.

brein
  • 1,409
  • 9
  • 11
  • Ok..I tried and is work..but how can I solve this problem in dev ? do I have to remove as suggested above? – LucaT May 19 '22 at 08:57
  • just don't worry about it, it's only a development issue that doesn't have repercussion once your code gets to production, here you can read more if you are interested: https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state – brein May 19 '22 at 09:00
  • 1
    Yes I see another thread chatting about this problem https://stackoverflow.com/questions/72238175/react-18-useeffect-is-getting-called-two-times-on-mount .. they fix it just for development with this useRef, But of course I see that in production the problem doesn't happen. – LucaT May 19 '22 at 09:02
  • yes, you can do that but in my opinion is a waste of time :) – brein May 19 '22 at 09:06
-3

If you use useEffect with an empty array you'll call only once when the component is rendered.

    useEffect(() => {
        dispatch(fetchItems()).then(res => console.log(res)).catch(err => console.log(err))
    }, [])
Petatet
  • 1
  • 2
  • useEffect(() => { dispatch(fetchItems()).then(res => console.log(res)).catch(err => console.log(err)) },[]) Modified like the code above..still get called two times. – LucaT May 19 '22 at 08:49
  • Ah, your component is re-rendered because your state is sync I think. You can try to test your state if it's empty and call your API and don't if it's filled (?) – Petatet May 19 '22 at 08:52