Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks equivalent for ComponentWillMount

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?

like image 715
Mike K Avatar asked Aug 06 '19 10:08

Mike K


2 Answers

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.

like image 92
hidden_4003 Avatar answered Nov 15 '22 06:11

hidden_4003


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
}
like image 37
Matias Heredia Sanchez Avatar answered Nov 15 '22 07:11

Matias Heredia Sanchez