How to setState false when a component rendered? – RN

I am new to application development. As seen below when “value” is false, I want the “Test” component to be rendered and the loading state to be false. But when I do as in the codes below, I get the error in the picture below. How do I set state to false without getting an error when this test component is rendered on the page?

enter image description here

import React, { useState } from 'react'
import { Text, View } from 'react-native'


const WordPage = () => {

    let value = false

    const [loading, setLoading] = useState(false)

    const Test = () => {
        setLoading(false)
        return (
            <Text>OFFLINE</Text>
        )
    }

    return (
        <View>
            {value ?
                <Text>ONLINE</Text>
                :
                <Test />
            }
        </View>
    )
}

export default WordPage

Answer

You can pass a callback as prop and call it once Test component is rendered.

import React, { useEffect, useState } from "react";
import { Text, View } from 'react-native'

const Test = ({ onRendered }) => {
  useEffect(onRendered, []);
  return <Text>OFFLINE</Text>;
};

const WordPage = () => {
  let value = false;
  const [loading, setLoading] = useState(false);

  return (
    <View>
      {value ? (
        <Text>ONLINE</Text>
      ) : (
        <Test
          onRendered={() => {
            setLoading(false);
          }}
        />
      )}
    </div>
  );
};

export default WordPage;
Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .