How to fulfill React useEffect missing dependency requirements?

Viewed 43

I can't figure out, how to fulfill the useEffect missing dependency requirements in the Dashboard component, where I only want to fetch Jobs once on render. Adding fetchJobs as a dependency or removing the dependency array causes infinite re-renders.

Dashboard.js:

...
import { useGlobalContext } from "../context/appContext";

const Dashboard = () => {
  const { user, logout, fetchJobs } = useGlobalContext();

  useEffect(() => {
    fetchJobs();
  }, []);

  return (
    ...
  );
};

export default Dashboard;

appContext.js:

...
const initialState = {
  user: null,
  jobs: []
};

const AppContext = React.createContext();

export const AppProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  ...

  const fetchJobs = async () => {
    try {
      const { data } = await API.get(`/jobs`);
      dispatch({ type: FETCH_JOBS_SUCCESS, payload: data.jobs });
    } catch (err) {
      console.log(err);
    }
  };

  ...

  return (
    <AppContext.Provider
      value={{
        ...state,
        login,
        logout,
        fetchJobs
      }}
    >
      {children}
    </AppContext.Provider>
  );
};

export const useGlobalContext = () => {
  return useContext(AppContext);
};

I tried to implement it with useCallback, but that didn't work either. Is this issue possibly related to using useContext?

I know that you can ignore the linting error by placing a // eslint-disable-next-line right above the dependency array, but that doesn't seem to be the right way to me.

Thanks for your help, I appreciate it.

Codesandbox: https://codesandbox.io/s/gracious-hamilton-ekftz3

0 Answers
Related