'React/Redux useEffect with dispatch fired multiple times

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.



Solution 1:[1]

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))
    }, [])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Petatet