How to fix this Maximum depth exceeded error with useEffect and useState?

0

Issue

I have events which is pulled from redux, and if the events array contains data, then updateData will be used to filter events into the state var data.

I have data and events both added to the dependency array as talked about here. but I’m still getting this error:

enter image description here

const SingleTable = () => {
    const events = useSelector(state => eventsSelector(state));
    const [data, updateData] = useState([]);
    const [sortCol, updateSortCol] = useState(0);
    const [sortDir, updateSortDir] = useState('ascending');

    useEffect(() => {
        const formattedArray = events ? formatLoss(events): [];

        events && updateData(formattedArray);
    }, [data, events]);

    //...

Thoughts, ideas?

Solution

Because you are executing useEffect callback whenever data changes and you are changing data in useEffect callback.

Remove data as dependency.

Use this code to fix it

const SingleTable = () => {
const events = useSelector(state => eventsSelector(state));
const [data, updateData] = useState([]);
const [sortCol, updateSortCol] = useState(0);
const [sortDir, updateSortDir] = useState('ascending');

useEffect(() => {
    const formattedArray = events ? formatLoss(events): [];

    events && updateData(formattedArray);
}, [events]);

//...

Answered By – Manu Bhardwaj

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More