1

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?

2
  • I refactored it to use hooks using both useEffect and useLayoutEffect, but the navigation now seems to happen only after the initial rendering, causing a flicker of another screen before the navigation takes place. Pretty hard to debug code we can't see Commented Jun 19, 2021 at 19:42
  • you can use a splash screen, then call SplashScreen.hide() when your app is ready - github.com/crazycodeboy/react-native-splash-screen Commented Jun 19, 2021 at 19:45

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.