Skip to content

Latest commit

 

History

History
41 lines (31 loc) · 1.92 KB

File metadata and controls

41 lines (31 loc) · 1.92 KB

useEffect 2 medium #react

by Pawan Kumar @jsartisan

Take the Challenge

What will be the output in console for the following code:

function App() {
  const [show, setShow] = useState(true)
  return <div>
    {show && <Child unmount={() => setShow(false)} />}
  </div>;
}

function Child({ unmount }) {
  const isMounted = useIsMounted()
  useEffect(() => {
    console.log(isMounted)
    Promise.resolve(true).then(() => {
      console.log(isMounted)
    });
    unmount(); 
  }, []);

  return null;
};

function useIsMounted() {
  const isMounted = useRef(false);

  useEffect(() => {
    isMounted.current = true;
    return () => isMounted.current = false;
  }, []);

  return isMounted.current;
}

Source


Back Share your Solutions Check out Solutions