• Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

76
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);
  }, []);
9 months 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
9 months 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.

9 months 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]);
9 months ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.