Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report

0

const Component = ({ isFilterMode }) => {
  const [active, setActive] = useState(() => isFilterMode ? null : 0);
  ...
}
about 4 years ago · Juan Pablo Isaza Report

0

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;} } );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!