useEffect with async function being called in a loop

My situation is this:

export default function Component({ navigation }) {
    const [ item, setItem ] = useState([]);
    
    useEffect(() => {
        AsyncStorage.getItem('someItem')
        .then(data => JSON.parse(data))
        .then(jsonData => {
            setItem(jsonData);
        })
        .catch(error => {});
    }, [item]);

The problem is that useEffect seems to be called in a loop, even when "item" doesn’t change. If I remove item from the dependencies array, it gets called once only and when item changes the component does not re-render. Is there a solution?

Solved like this:

export default function Component({ navigation }) {
        const [ item, setItem ] = useState([]);
        const [ update, setUpdate ] = useState(false);

        const handleUpdate = () => {
            setUpdate(!update);
        }
        
        useEffect(() => {
            AsyncStorage.getItem('someItem')
            .then(data => JSON.parse(data))
            .then(jsonData => {
                setItem(jsonData);
            })
            .catch(error => {});
        }, [update]);

And then calling handleUpdate (or passing it to a child component and letting the child call it) when I want to update item’s state.

101 thoughts on “useEffect with async function being called in a loop”

Leave a Comment