Search code examples
reactjsreact-hooksuse-effect

React useEffect Hook complains about missing dependency


I have two components that talk to each other. In component A I have a list of locations and whenever a user clicks on one of the locations in this component this filters a list of properties in component B dependent on the clicked location. This works, so far so good. But in component B I use a useEffect hook to check for the selectedLocation variable that comes to it via props from component A so I can update the state. And in this useEffect() call VS Code complains that "React useEffect Hook has a missing dependency "...dataState". But of course I can't put the dataState in to the dependency array because it would cause an infinite loop. And by the way, dateState is managed via a useState Hook. Here is my useEffect hook:

    //  If there is a new selected location from the treeview, update the grid state
useEffect(() => {
    const newState: State = {
        ...dataState,
        filter: {
            logic: 'and',
            filters: [
                {
                    field: 'location',
                    operator: 'contains',
                    value: selectedLocation,
                },
            ],
        },
    };
    setDataState(newState);
}, [selectedLocation]);

Any help would be appreciated.


Solution

  • Try to set dataState like that:

    useEffect(() => {
        setDataState(oldDataState => ({
            ...oldDataState ,
            filter: {
                logic: 'and',
                filters: [
                    {
                        field: 'location',
                        operator: 'contains',
                        value: selectedLocation,
                    },
                ],
            },
        }));
    }, [selectedLocation]);
    

    This way it would be considered as a parameter instead of a dependency.