Understand State in <React /> Hooks

Started off with react and still confused ūü§Ē about the idea of States? Worry No More.

As a prerequisite, you should have your basic react app setups Ready.

You see most times react components needs to manipulate data. To achieve this, come the idea of STATE in React.

Today, we are going to understand how to use this special react component called state.

State is a special object that holds dynamic data. This means that state can change over time based on the user action or certain events.

States are private and must only belongs to its component where it is defined.

So except data are passed as a PRO , we cannot have access from other components. Read more about Props here

Using the react hooks:

  • Import the the useState hook from react and inside your component function
  • Declare a new state variable (in our case below, ‚Äėcount‚Äô ) giving it any argument (array, strings, integer or even object).
  • The first argument passed into it is our initial state. Here ours is 0
import React, { useState } from 'react'

const App = () => {
  const [count, setCount] = useState(0)

  return (
    <div>
      {count}
    </div>
  )
}

export default App

The useState() returns a pair values: the current state and a function to update it, hence

const [count, setCount] = useState(0)

The count variable now store the value 0 in its component state and with the setCount function, the state can be manipulated.

We can use the function to increase the current states of the count progressively at each click as shown in the button here

import React, { useState } from 'react'

const App = () => {
  const [count, setCount] = useState(0)

  return (
    <div>
      {count}
      <div className="">
        <button onClick={()=> setCount(count+1)}>Click me</button> 
      </div>
    </div>
  );
}

export default App

See as the setCount() function is been used to increase the count by 1 for each state.

Thanks for reading!!!

No Comments Yet