React Native

What is the purpose of the useEffect hook in React Native?

Medium
5
Added
The useEffect hook is used for side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM.

Solution Code

React Native
-- Example Code --
import React, { useState, useEffect } from "react";
import { View, Text } from "react-native";

const App = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch("https://api.example.com/data")
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <View>
      <Text>{data ? data.message : "Loading..."}</Text>
    </View>
  );
};

export default App;
Explanation
This code demonstrates how to use the useEffect hook to fetch data when the component mounts.

Guided Hints

{'hint': 'Use useEffect for side effects.'}
{'hint': 'The second argument is a dependency array.'}