'How can I render only once an Alert component in react native?
How can I render only one time an Alert component in react native if my dashboardScreen is being render many times?
I'm using Context api, if I dispatch an action it causes another render, if I use a useState it causes another render/renders, any idea will be highly appreciate it.
**AppContext.js**
export const AppContext = createContext();
export const AppProvider = ({ children })=> {
const [ state, dispatch ] = useReducer( appReducer, appInicialState);
return (
<AppProvider.Provider value={{
...state,
}}>
{ children }
</AppProvider.Provider>
)
}
**Dashboard.js**
export const Dashboard = () => {
const { state, dispatch } = useContext( AppContext );
const [showAlert, setShowAlert] = useState(true);
const handleCancelPressed = () => {
dispatch({
type: 'cancelPressed',
payload: {
userInfo: false,
}
});
}
const handleAcceptPressed = () => {
dispatch({
type: 'acceptPressed',
payload: {
userInfo: true,
}
});
}
return (
<View style={styles.container}>
{showAlert && (
Alert.alert(
"Alert Title",
"My Alert Msg",
[
{
text: "Cancel",
onPress: handleCancelPressed,
},
{
text: "Ok",
onPress: handleAcceptPressed ,
},
],
{
cancelable: true,
}
);
)}
</View>
)}
Solution 1:[1]
useEffect
is the way which can solve your problem for rendering it only once.
const [showAlert, setShowAlert] = useState(null);
useEffect(()=>{setShowAlert(true)},[])
The empty bracket denotes that, value for 'showAlert' will be set only once.
You should read useEffect in detail for implementing this properly.
I am not trying this example in any coding environment, I have only shared a proof of concept for you to work upon.
Hope this helps,
Regards, Shameel Uddin
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Shameel Uddin |