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

174
Views
React make useState initial value conditional

I am trying to set initial state based on data from props.

const Calculate({data}) => {
  const [number, setNumber] = data === 'end' ? useState(5) : useState(0);

  return (...)
}

This gave me an error: React Hook "React.useState" is called conditionally. React Hooks must be called in the exact same order in every component render.

So I decided to update my code with useEffect:

const Calculate({data}) => {
  const [number, setNumber] = useState(0);

  useEffect(() => {
     if (data === 'end') {
       setNumber(5)
     }
   }, []);
} 

However I'd rather not set the state initially to zero if I don't need to.

Alternatively can I solve it by making the initial value conditional?

const Calculate({data}) => {
  const [number, setNumber] = useState(data === 'end' ? 5 : 0);

  return (...)
}

Are there any side effects to this? Why would this work and not my original attempt?

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

0

You can use a ternary inside your useState hook and it will work fine. However, it is better to wrap it inside a function expression in the following manner.

const [number, setNumber] = useState((data) => data === 'end' ? 5 : 0)

The function expression in above code snippet will be evaluated only once while setting the initial state. There is an upside to wrapping your ternary operator inside the function expression.

Suppose that instead of data === 'end' ? 5 : 0 you want to use the results of an expensive computation to set the initial state, in such a case you can wrap it inside a function expression like:

const [number, setNumber] = useState(() => expensiveFunction())

This is better because () => expensiveFunction() will return a function which will only be evaluated once during the initial render. Whereas if you don't wrap the expensiveFunction inside a function expression, it will be evaluated each time your component renders and block the execution of code until expensiveFunction returns a value.

This approach is also known as Lazy initialization.

about 4 years ago · Juan Pablo Isaza Report

0

Are there any side effects to this? Why would this work and not my original attempt?

No there are no side effects, that is the way to go in your situation. It didn't work in your case because you violated one of the rules of hooks:

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)

Initially your useState calls themselves were wrapped inside a condition and that was a problem. That is not the case anymore with your newer approach.

about 4 years ago · Juan Pablo Isaza Report

0

If data can ever change.... The only thing you need to make sure you handle is that the data being passed down is not null, but rather undefined if it doesn't exist.

Your useEffect should have data in the dependency array to re-render the component upon any change.

const Calculate({data = 0}) => {
  const [number, setNumber] = useState(data);

  useEffect(() => {
     setNumber(data)
   }, [data]);
} 
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!