useState() in React

Wondered what State in React is and why it is being used in the applications?

Let's start with a discussion then,

So think of a state as the correct way of defining variables in React and it will allow us to have some memory inside each component. (Easy to remember..!)

And the fun fact is, previously only class-based components support the state and functional components were limited but React hooks came into the picture (from React 16.8 version) which allows us to use state.

Let’s start looking into a simple example of how can we use state in React with Hooks. useState is the hook will be using here in our example.

Example -

import React, {useState} from “react”

const IncrementCounter = () ⇒ {
  const [increment, setIncrement] = useState(0)
  const handleClick = () ⇒ {
    setIncrement(increment + 1)
  }

  return (
    <div>
        <h1>Incremented Value - {increment}</h1>
        <button onChange={handleClick}>Click to Increment</button>
    </div>
    )
}

export default IncrementCounter

Let’s discuss how the above example is working,

  • First, import useState from react
  • Declare the state variables in the following manner,
  • const [increment, setIncrement] = useState(0)
  • increment → initial state value
  • setIncrement → final state value
  • useState(0) → initialized with initial value
  • handleClick() → function is declared to manipulate the state of the variable and set the final to incremented value.

I hope this small post will be useful to you! Of course, there is much more concept to cover here which I'll do it later!

Feel free to reach out me! LinkedIn