0

I would like to call a useState function inside a component. I created a function named 'increase' and called useState function inside it to change the state value to 10. But when i call the function it throws error. Can anyone give me an explanation about why this happens. The code is as follows. Thanks in Advance!

import React, {useState} from 'react'

function ComponentOne() {
    const[value,setValue]=useState(0);
    let increase=()=>{
        setValue(10)
    }
    increase();
  return (
    <div>
        <h3>{value}</h3>
    </div>
  )
}

export default ComponentOne
  • 1
    Can you send the error you get? – indyteo Feb 27 '23 at 16:12
  • 3
    The error is probably trying to tell you what the problem is. Have you tried reading the error message and searching it on your favorite search engine? *At a glance* I would expect this code to produce an error about too many re-renders, because you're updating state on *every render*. Did you mean to update state only after the *first* render? Maybe you're looking for the `useEffect` hook? – David Feb 27 '23 at 16:13
  • 1
    Does this answer your question? [Updating state to the same state directly in the component body](https://stackoverflow.com/questions/74034014/updating-state-to-the-same-state-directly-in-the-component-body) – Konrad Feb 27 '23 at 16:16
  • Yo should not set the state in the component, you probably want to use an interval that runs periodically to update your value or add a button or input that can change your value. – jean182 Feb 27 '23 at 16:20
  • @indyteo Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. – shaijuelayidath Feb 27 '23 at 16:29
  • I asked about something similar some time ago https://stackoverflow.com/questions/74034012/why-doesnt-setstate-usestate-correctly-recognize-same-value-in-the-initial-re tl;dr; you have to use `useEffect` – Konrad Feb 27 '23 at 16:30
  • 1
    See the comment made by @David then, he explained the reason of this and gave you hints about how to avoid it ;) – indyteo Feb 27 '23 at 16:30
  • @David I am curious to know why the state is updating in every render once we call the function. Should it be increase 10 by every render and assign it to the 'value'. Its really tricky to understand the concept here. – shaijuelayidath Feb 27 '23 at 16:51
  • @Konrad I am reading the Q&A you sent. I takes lot of time to read and understand the concept. I am reading slowly and trying to understand it. Thanks for Sharing. – shaijuelayidath Feb 27 '23 at 16:53
  • @shaijuelayidath: *"I am curious to know why the state is updating in every render"* - Because the entire component is a function, and that function is called on every render. Within that function you define and invoke `increase`. So it will be defined and invoked on every render. What are you intending to do instead? Invoke `increase` when a specific event occurs? – David Feb 27 '23 at 17:07

0 Answers0