S
S
Shakir Darion2019-08-06 14:22:23
React
Shakir Darion, 2019-08-06 14:22:23

React equivalent hooks for ComponentWillMount Ask?

I looked here , but the selected answer doesn't answer the question. I'm looking for a componentWillMount() equivalent to perform logic similar to:

useEffect(() => {
  if (condition) {
    // do stuff
  }
}, []);

The problem with the above is that the component renders for a fraction of a second before executing the useEffect block of code.
Is there a way around this? Without using useEffect in the main App component or creating a custom hook?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Spirin, 2019-08-06
@shakiriker

First, componentWillMount is not recommended for use. Secondly, it will not protect you in any way from an additional render call if it is an asynchronous operation, and it is not needed for synchronous ones.
Feel free to use componentDidMount and useEffect.
And you can fence yourself off from unnecessary calculations, for example, like this:
if (!someCondition) return null;

S
SANTA2112, 2019-08-06
@SANTA2112

Try

useLayoutEffect(() => {
  if (condition) {
    // do stuff
  }
}, []);

partial equivalent

S
SwoDs, 2017-12-12
@SwoDs

Eh, why did you have to post here in order to immediately find this font, before that I couldn’t find it ...
It looks like Rodeo

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question