I need to display the background as red only for a second once the user clicks on the button that updates the state. Once the state is updated the displayed values change. So before this happens I need to change the background to a particular color(green/red/blue) before the state changes but only for a second. I tried using setTimeOut() but might not be using it correctly
const [rightOptionBgColor1, setRightOptionBgColor1] = useState('#95d4ed');
async function onPressOptionRight1() {
setRightOptionBgColor1('green');
};
<TouchableWithoutFeedback onPress={onPressOptionRight1}>
<View style={[styles.twoOptions, { backgroundColor: rightOptionBgColor1 }]}>
<Text style={styles.textStyles} >{rightAns}</Text>
</View>
-------Edited Updated Answer----------
I have created a working snack of what you want to achieve but before viewing it read the answer below. here's snack link
https://snack.expo.dev/@crystalarcus/usestate-with-timeout
You can easily achieve it with
useEffecthook.useEffectcan be used to do something after the specificuseStatechanges.useEffecttakes 2 arguments, first thefunctionbe executed every time state change, second aarrayof variables ( useState ). Syntax is simple :useEffect( function , [array of varaibles])Everytime variables in
arraychange,useEffectexecutesfunctionpassed into it.Instead of
TouchableWithoutFeedback, I suggest you usePressablecomponent.NOTE : ALWAYS USE
useEffectright above return statement of component and below otheruseStatevariables.So This is how you use it:
Explanation :
As you see, useState
isAnsweredis passed inuseEffectat the end. This means the function passed to it will be triggered everytimeisAnsweredchanges.setTimeouthave been used to wait and function passed inside it will be executed after timeout.Hope this helps !!