react cleanup function code example

Example 1: useeffect with cleanup

useEffect(() => {
	//your code goes here
    return () => {
      //your cleanup code codes here
    };
  },[]);

Example 2: useeffect cleanup function

function App() {
  const [shouldRender, setShouldRender] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setShouldRender(false);
    }, 5000);
  }, []);

  // don't render
  if( !shouldRender ) return null;
  // JSX, if the shouldRender is true
  return <ForExample />;
}

Example 3: react cleanup meas

Network requests, manual DOM mutations, and logging are common examples
of effects that don’t require a cleanup. We might want to set up a
subscription to some external data source. In that case, it is
important to clean up so that we don’t introduce a memory leak!