background image
James DiGioia

my little web home

useEffect dependency array issues

useEffect(() => {
  refreshCart();
}, []);
const refreshCart = () =>
  api.getCart().then(cart => setState(cart));
const refreshCart = useCallback(
  () => api.getCart().then(cart => setState(cart)),
  [],
);
const refreshCartRef = useRef(null);

if (!refreshCartRef.current) {
  refreshCartRef.current = () =>
    api.getCart().then(cart => setState(cart));
}

useEffect(() => refreshCartRef.current(), []);
useEffect(() => {
  refreshCart();
  // refreshCart is recreated fresh, but we only want to
  // do this on initial render, so we're going to provide
  // an empty array here so it only runs once.
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);