useEffect
is a React Hook that allows you to perform side effects in functional components. It's widely used in both React and React Native to handle tasks such as data fetching, subscriptions, timers, or manual DOM manipulations.
Here's an overview of how to use useEffect
in React Native:
useEffect(() => {
// Effect code here
return () => {
// Cleanup code here (optional)
};
}, [dependencies]);
Parameters
- Effect function: This is the function where you perform your side effects.
- Cleanup function: This is optional and is used to clean up
after the effect (e.g., unsubscribe or cancel a network request).
- Dependencies array: Determines when the effect should re-run.
- An empty array
[]
runs the effect only once after the component mounts. - Omitting the array runs the effect after every render.
- Including dependencies
[dependency1, dependency2]
runs the effect when one of the dependencies changes.
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
const App = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts/1') // Example API
.then((response) => response.json())
.then((json) => setData(json));
}, []);
return (
<View style={{ padding: 20 }}>
{data ? (
<>
<Text>Title: {data.title}</Text>
<Text>Body: {data.body}</Text>
</>
) : (
<Text>Loading...</Text>
)}
</View>
);
};
export default App;
fetch API With ASYNC & Try Catch
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
const FetchDataExample = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos');
const result = await response.json();
setData(result);
} catch (error) {
console.error(error);
}
};
fetchData();
}, []); // Empty array means this runs once after the component mounts
return (
<View>
<Text>{data ? JSON.stringify(data) : 'Loading...'}</Text>
</View>
);
};
export default FetchDataExample;