call an asynchronize function in the beginning of a component code

I am developing a react-native project.

I have a functional component:

const MyComponent = () => {
  
   // the checkData function is an asynchronize function
   const { checkData } = useContext(MyContext);

   // I have to wait for the result since the rendering part use the result as you can see below
   const isValid = await checkData();

   return (<View>
       <MySubComponent isValid={isValid}/> 
   </View>)
}

As you can see above, I have to call an asynchronize function checkData & using the result for rendering MySubComponent. I can’t use await like above code shows. I also tried making MyComponent an async functional component like const MyComponent = async()=>{...} but app crashes.

What is the correct way to call an asynchronize function in functional component & use its result for rendering sub component?

Answer

You can use useEffect to load async data and use a local state to track the value. for that you can try useState hook.

Set the initial value to null so you can show some kind of loading screen if the state is equal to null. If not ( That means async process updated the value to true or false ) then you can show the component.

const MyComponent = () => {
  
   // the checkData function is an asynchronize function
   const { checkData } = useContext(MyContext);
   const [isValid, setValidity] = useState(null);
   
   
   useEffect(() => {
     async function init() {
         const isValid = await checkData();
         setValidity(isValid);
     }
     init();
   }, [])

   return (
   <View>
       {isValid != null ? <MySubComponent isValid={isValid}/> : <SplashScreen />} 
   </View>)
}