Rishabh876
Rishabh876

Reputation: 3180

useState keeps getting reset to initialValue on re render

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

Upvotes: 6

Views: 13239

Answers (1)

Ori Drori
Ori Drori

Reputation: 191936

It's not actually resetted to the initial value. You just keep calling the function that 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()

Upvotes: 5

Related Questions