I'v taken a look here but the selected answer does not answer the question. I'm looking for a componentWillMount()
equivalent to execute logic similar to:
useEffect(() => {
if (condition) {
// do stuff
}
}, []);
The issue with the above is that the component renders for a split second before executing the useEffect
block of code.
Any way to get around this? Without having the useEffect run in the main App
component or creating a custom hook?
From reactjs docs:
This lifecycle was previously named componentWillMount. That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.
UNSAFE_componentWillMount() is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering. Generally, we recommend using the constructor() instead for initializing state.
So there is no more equivalent for componentWillMount, you can modify render method to return null/placeholder until your init conditions are met and set state in useEffect. You can look into react suspense too.
you could transform your component into a class or you could do a workaround like this:
let firstRender = true
const yourComponent = () =>{
useEffect(() =>{
firstRender = false
},[])
if (firstRender){
// willmount code
}
return null
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With