Actually, I want to add more cases here, and I am going to make reusable custom hooks.
1.Care about extra dom render
It will not cause extra dom render
const useOptimizedComponentWillMount = callback => {
const mounted = useRef(false)
if (!mounted.current) callback()
useEffect(() => {
mounted.current = true
}, []);
};
Note: You might want mounted && mounted.current
in typescript
2. Don't care about extra dom render
this is exactly Tony answer
const useComponentWillMount = callback => {
const [mounted, setMounted] = useState(false)
if (!mounted) callback()
useEffect(() => {
setMounted(true)
}, [])
};
Usage
const App = () => {
useComponentWillMount(() => console.log("will mount"))
return console.log("render-dom") || <div>Layout</div>
};
// will mount
// (2)render-dom
const App = () => {
useOptimizedComponentWillMount(() => console.log("will mount"))
return console.log("render-dom") || <div>Layout</div>
};
// will mount
// render-dom