'Custom hook not updating in component

I have a custom hook that looks roughly like this:

export default function useMyHook() {
  const [foo, _setFoo] = useState([]);
  const [bar, setBar] = useState(null);
  const setFoo = (arg) => {
    _setFoo(arg);
    const newBar = getBar(arg);
    setBar(newBar);
  };

  useEffect(() => {
    console.log(bar); // this prints when bar changes
  }, [bar]);

  return {
    foo,
    bar,
    setFoo,
  };
}

And this hook is used like this:

export const function MyComp(): React.MixedElement {
  const {foo} = useMyHook()

  console.log(foo) // prints null once
  useEffect(() => {
    console.log(foo) // doesn't print
  }, [foo])

  return foo ? (
    <div>This doesn't render</div>
  ) : (
    <div>This renders</div>
  )
} 

The setFoo() is called in different component to set foo. When that happens, bar changes, and runs the useEffect callback, but not in the component.

What is happening here, and how can I fix it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source