useeffect to set state code example
Example 1: how to setstate in useeffect
React.useEffect(() => {
let didCancel = false;
// ...
// you can check didCancel
// before running any setState
// ...
return () => {
didCancel = true;
};
});
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 />;
}