phsource
phsource

Reputation: 2446

How to run code in React function component before first render, like in the constructor of a class component?

I have a piece of code in React Native that currently runs on app start. Within a class component constructor. It checks a bunch of conditions using the React Navigation state and then navigates somewhere.

class MyComponent<Props> {
  constructor(props: Props) {
    super(props);
    // Some initialization code
  }
}

I refactored it to use hooks using both useEffect and useLayoutEffect, but the code run now seems to happen only after the initial rendering, causing a flicker of another screen before the navigation takes place.

function MyComponent() {
  useEffect(() => {
    // Do some stuff
  }, []);  

  return null;
}

Is there some equivalent to the class constructor that runs before rendering in function components?

Upvotes: 1

Views: 2607

Answers (1)

phsource
phsource

Reputation: 2446

Ah, I figured out a solution.

Before, I'd written the code this way:

function MyComponent() {
  useEffect(() => {
    // Do some stuff
  }, []);  

  return null;
}

Turns out the equivalent is just running your code in the function itself, since that runs before the actual rendering-to-screen.

function MyComponent() {
  const initializedRef = useRef(false);
  if (!initializedRef.current) {
    initializedRef.current = true;
    // Do some stuff
  }

  return null;
}

This seems to be as fast as the run-in-constructor code I used to have.

Upvotes: 2

Related Questions