Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set initial useState value in React based on props

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?

like image 501
cts Avatar asked Sep 06 '25 03:09

cts


2 Answers

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);
like image 179
Amila Senadheera Avatar answered Sep 07 '25 21:09

Amila Senadheera


const Component = ({ isFilterMode }) => {
  const [active, setActive] = useState(() => isFilterMode ? null : 0);
  ...
}
like image 37
Adnan Irfan Avatar answered Sep 07 '25 19:09

Adnan Irfan