Changing States

Like the JavaScript we may apply the same approach here:

import './App.css'

function App() {
  let count=1;
  function inc(){
    count++;
    console.log(count);
  }
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={inc}>INCREMENT</button>
    </div>
  )
}

export default App

This won’t change the state of the count variable, hence the increment functionality we require fails.

useState Hook

useState is a hook used to create a state variable in react functional component

useState is a function which returns an array of two elements

  1. state variable : variable which stores the data which can be changed
  2. state setter function : the function to update the state variable

Untitled

The initial state can be used to initialise the state variable.

<aside> 💡 We are required to import the useState from the react

import { useState } from 'react'

</aside>

Untitled

Our code can be corrected by using the useState Hook:

import { useState } from 'react'
import './App.css'
function App() {
  const [count, setCount] = useState(0);
  const inc = () => {
    setCount(count + 1);
  }
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={inc}>ADD</button>
    </div>
  )
}
export default App

https://pavancos.github.io/LearnWebDev/Day-8/dom/

We can use the state setter anywhere in the component to change the state of the state variable:

import { useState } from 'react'
import './App.css'
function App() {
  const [count, setCount] = useState(0);
  const inc = () => {
    setCount(count + 1);
  }
  const dec = () => {
    setCount(count - 1);
  }
  const res = () => {
    setCount(0);
  }
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={inc}>INCREMENT</button>
      <button onClick={dec}>DECREMENT</button>
      <button onClick={res}>RESET</button>
      
    </div>
  )
}
export default App

https://usestatehook.vercel.app/

When we have to work with an object, and we intend to change a single element in it, we have to create a copy of the object and then change the single element and return to avoid resetting of all the other elements.