Home > Net >  What is the best way of assigning a variable from an object value in React?
What is the best way of assigning a variable from an object value in React?

Time:03-08

I want to know what the better option is when getting values out of an object:

const [currentMonth, setCurrentMonth] = React.useState(getCurrentMonth(language).label)

or:

const { label: labelMon } = getCurrentMonth(language)
const [currentMonth, setCurrentMonth] = React.useState(labelMon)

I want to use the value only once to set the initial state.

CodePudding user response:

You have to use this once it happens

 useEffect(() => {
const { label: labelMon } = getCurrentMonth(language)
   setCurrentMonth(labelMon )
  },[]);

CodePudding user response:

When you want to set initial value of state based on some value get from props of custom function execution you should perform that inside of useEffect hook

const [currentMonth, setCurrentMonth] = React.useState(null);
useEffect(() => {
    // Here you can call your function 
    const { label } = getCurrentMonth(language);

    setCurrentMonth(label);
}, [])
  • Related