setstate to false after 10 sec react native
How to set state to false after 10 seconds in React Native
If you are working with React Native and you want to set state to false after a specific time, you can easily achieve it using the setTimeout()
function. Here's how you can do it:
Method 1: Using setTimeout()
import React, { useState, useEffect } from 'react';
import { Text, View } from 'react-native';
const App = () => {
const [showText, setShowText] = useState(true);
useEffect(() => {
setTimeout(() => {
setShowText(false);
}, 10000); // set time in milliseconds
}, []);
return (
<View>
{showText ? <Text>Hello World!</Text> : null}
</View>
);
};
export default App;
useState()
hook is used to define a state variableshowText
.useEffect()
hook is used to call thesetTimeout()
function.- The
setTimeout()
function is used to set the state ofshowText
to false after 10 seconds (10000 milliseconds). <Text>
component is rendered conditionally based on the value ofshowText
.
This method is simple and easy to understand. However, if you have multiple components that depend on the same state variable, you may need to pass the state variable as a prop to each component which can be tedious.
Method 2: Using Context API
// App.js
import React, { useState } from 'react';
import { Text, View } from 'react-native';
export const AppContext = React.createContext();
const App = () => {
const [showText, setShowText] = useState(true);
const value = { showText, setShowText };
return (
<AppContext.Provider value={value}>
<View>
<Text>Hello World!</Text>
</View>
</AppContext.Provider>
);
};
export default App;
// ChildComponent.js
import React, { useContext, useEffect } from 'react';
import { Text, View } from 'react-native';
import { AppContext } from './App';
const ChildComponent = () => {
const { showText, setShowText } = useContext(AppContext);
useEffect(() => {
setTimeout(() => {
setShowText(false);
}, 10000); // set time in milliseconds
}, []);
return (
<View>
{showText ? <Text>Hello World!</Text> : null}
</View>
);
};
export default ChildComponent;
useState()
hook is used to define a state variableshowText
.AppContext
is created using theReact.createContext()
function.- The state variable
showText
and the function to update itsetShowText
are passed as values to the context provider. ChildComponent
component uses theuseContext()
hook to get the state variableshowText
and the function to update itsetShowText
.- The
setTimeout()
function is used to set the state ofshowText
to false after 10 seconds (10000 milliseconds). <Text>
component is rendered conditionally based on the value ofshowText
.
This method is useful when you have multiple components that depend on the same state variable. You can avoid prop drilling by using the Context API.
Choose the method that suits your needs and implement it accordingly. Happy coding!