Mike K
Mike K

Reputation: 6491

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?

Upvotes: 4

Views: 10644

Answers (3)

herlambang
herlambang

Reputation: 178

It's too late for you, but maybe will help the others

There's no equivalent of ComponentWillMount for hooks, BUT you can simulate the behavior by creating a hook and using useRef like this

export const useWillMount = (fn) => {
  const willMount = useRef(true)
  
  if (willMount.current && fn && typeof fn === 'function') {
    fn()
  }
  
  willMount.current = false
}

Usage

const Component = (props) => {
  useWillMount(() => {
    // Do stuff for componentWillMount here
  })

  ...
}

Upvotes: 2

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
}

Upvotes: 2

hidden_4003
hidden_4003

Reputation: 1799

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.

Upvotes: 4

Related Questions