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

239
Views
Assigning value at useState() declaration vs useEffect()

I have been using these two ways interchangeably however I am not sure which one is the more correct. their behavior seems to be the same but I am sure there is a use case for each. Anyone can help me understand what's the proper use for each case?

const [customer, setCustomers] = useState(props.location.state);
  useEffect(() => {
    setCustomers(props.location.state);
  }, []);
about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

You should normally stick to the first one. Calling the setter of useState may lead to undesired re-renders and decreased performance.

In the first block the customer is initialised directly and no re-render happens. The setCustomer method will change the state and rerender the component. In the end the whole function will run twice which you can verify with a console.log.

const [customer, setCustomers] = useState(0);

useEffect(() => {
  setCustomers(15);
}, []);

console.log(customer) // will first output 0 and then 15
about 4 years ago · Santiago Gelvez Report

0

Assuming in the second case, you have this as your useState statement:

const [customer, setCustomers] = useState();

The second one sets the value of customer on componentDidMount. So in the initial render, you will not have the appropriate value in your customer variable. But yes, very soon after that the correct value will be set because of the code written in useEffect.

To clear it up, there will be 2 renders here (because the state variable value changes). In the first one, that won't be the case since the state variable has only one value from beginning.

about 4 years ago · Santiago Gelvez Report

0

The first one is more effective.

const [customer, setCustomers] = useState(props.location.state);

If you use second one (by using useEffect), your component will be re-rendered again.

That's, your state variable customer will be updated in useEffect after DOM is initially rendered, this leads the 2nd re-render of the component.

But if you want customer to be updated by props.location.state, you need to add useEffect hook like the following.

useEffect(()=> {
    setCustomers(props.location.state);
}, [props.location.state]);
about 4 years ago · Santiago Gelvez 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!