Home > front end >  How to set initial useState value in React based on props
How to set initial useState value in React based on props

Time:11-18

I currently set my active state to 0:

const [active, setActive] = useState(0);

but I'm wondering how I can set the initial value to null if one of my component props: isFilterMode is true? So the initial state is "dynamic" based on the props?

CodePudding user response:

Try like below

const [active, setActive] = useState(props.isFilterMode ? null : 0);

Or

using a callback function (lazy initialisation)

const [active, setActive] = useState(() => props.isFilterMode ? null : 0);

CodePudding user response:

you can define an expression with a return value as an argument for useState. With a ternary operator like props.isFilterMode ? null : 0 you would return null if the value of props.isFilterMode evaluates to true and 0 otherwise. So in useState you would have:

  const [active, setActive] = useState(props.isFilterMode ? null : 0);

And like Amila suggested in the other answer you can use a callback as a parameter to useState and whatever is evaluated and returned from that callback would be your initial state using arrow functions you would do something like:

 const [active, setActive] = useState(() => props.isFilterMode ? null : 0);

or more explicitly but with longer code:

  const [active, setActive] = useState(() => { if(props.isFilterMode){ return null;} else { return 0;} } );

CodePudding user response:

const Component = ({ isFilterMode }) => {
  const [active, setActive] = useState(() => isFilterMode ? null : 0);
  ...
}
  • Related