Home > Software design >  why state is not initializing with given value?
why state is not initializing with given value?

Time:10-14

latest value is coming from props, but when it is added as the initial value for state it is not showing up.

enter image description here

 import React, { useRef, useState } from "react";
 //import config from "../../../../../../config";
 //import { getAuthToken } from "../../../../../utils/auth";
 import styles from "./ContentRowPrice.module.css";

 const ContentRowPrice = (props) => {
   const [priceInput, setPriceInput] = useState(props.price);
   // const priceInput = useRef();

   // const handleBlur = () => {
   //   const price = parseFloat(priceInput.current.value);
   //   if (props.price === price) {
   //   } else {
   //     props.onPaywallChange(price);
   //   }
   // };

    const classes = styles["contentrowprice-input"];
    return (
      <>
        <span>{props.price}</span>
        <span>{priceInput}</span>
        <input
          id={`paywall_${props.price}_${props.id}`}
          type="number"
          min="0"
          step="0.01"
          // ref={priceInput}
          // defaultValue={props.price}
          value={priceInput}
          className={classes}
          // onBlur={handleBlur}
        />
    </>
  );
};
export default ContentRowPrice;

one Thing that I realized that the value 10 is actually coming from input that was previously in the place of the above input.

enter image description here

CodePudding user response:

The first render of a React component is with empty values, this is the moment when react component creates component and a state with useState hook.

When you assign it in useState, it will not change in second (or later) re-renders without a useEffect hook.

  useEffect(() => {
   setPriceInput(props.price);
  }, [props.price]);

More about this problem, you can read here: https://medium.com/@digruby/do-not-use-props-as-default-value-of-react-usestate-directly-818ee192f454

  • Related