Search code examples
reactjsreact-hookssetstate

How do I use React setState() to set the state to a specific value that is a constant?


  const [number, setNumber] = useState(0);
  let newNumber = 200;

  useEffect(() => {
    setNumber(number = newNumber);
  }, [])

I believe I'm misunderstanding something about how state works in React.js. If I set the above code's setNumber(number + 1) section to '+ 1' like so then number becomes '201' but if I set it to '= newNumber' I get a 'TypeError: Assignment to constant variable' error. Why is this the case? And shouldn't the error be something else since newNumber isn't a constant variable using the 'const' tag?


Solution

  • The setNumber function accepts a value you want to set your state to. So If you want to set number to the value of newNumber you would do setNumber(newNumber)