useState keeps getting reset to initialValue on re render

Viewed 5874

So my code for the screen looks something like this. I have a useState amount that keeps getting reset to initialValue on re-renders. I have around 3 useEffects. One of them is in the sample code here where I am getting the amount from db and setting it using setAmount.

const ConfirmPaymentDialog = props => {
   const getInitialVal = () => {
      console.log('Initial Amount: 0');
      return conversions.numberToBigNumber(0);
   };
   const [amount, setAmount] = useState<BigNumber>(getInitialVal());

   useEffect(() => {
       getAmountToPay();
   },[]);

   const getAmountToPay = async () => {
    const amount = await myDbModule.getAmount(customer.id);
    console.log('DB Amount: ' + amount?.toString());
    setAmount(amount || conversions.numberToBigNumber(0));
  };

   useEffect(() => {
   ...
   }, [isInputTextFocused])

  console.log('Rendering');
  return (<View>...</View>);
}

When I open this screen.I get following console logs

 LOG  Initial Amount: 0
 LOG  Rendering
 LOG  DB Amount: 500
 LOG  Initial Amount: 0
 LOG  Rendering
 LOG  Initial Amount: 0
 LOG  Rendering
 LOG  Initial Amount: 0
 LOG  Rendering
 LOG  Initial Amount: 0
 LOG  Rendering
 LOG  Initial Amount: 0
 LOG  Rendering

How do I stop my useState from resetting back to default value on re-renders

1 Answers

It's not actually resetted to the initial value. You just keep calling the function the generates the initial value. Instead of calling it, pass it as callback (see lazy initial state) to the useState() hook, and it will be called once:

const [amount, setAmount] = useState<BigNumber>(getInitialVal); // getInitialVal instead of getInitialVal()
Related