Floxus Education Team Blogs

Floxus Education Team Blogs

Quick Guide on React useState() Hook

Photo by Lautaro Andreani on Unsplash

Quick Guide on React useState() Hook

Floxus Education's photo
Floxus Education
Ā·Jun 19, 2022Ā·

5 min read

Table of contents

  • How to Handle useState??
  • useState()

In React, Hooks are in-built functions that allow React Developers to use React State and lifecycle methods inside the functional components.

  • One of the most important parts of any application is managing the state. Most code that is written in some way deals with modifying or reading state, so understanding how to manage state is incredibly important.
  • Before hooks were introduced the only way to modify state was with class components and this.state , but React has introduced hooks, specifically the useState hook šŸ¤©, which is a new way to handle state inside of functional components.

How to Handle useState??

When you take an initial look at the React Hooks documentation, youā€™ll see that there are several Hooks that we can use for our applications. You can even create your own custom hook.

In this Section, we basically deal with the useState hook:-

  • useState:- It allows us to have state variables in functional components and developers can manipulate, update the state inside the component without converting it to the class component.

Before going further let's see Some advantages of React Hooks:-

  • React Hooks are easier to work with and to test and make the code look cleaner, easier to read.
  • Avoiding ES6 classes
  • In react class component, we split our work into different life-cycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount, but in hooks, we can do everything in a single hook called useEffect.

Letā€™s start from Scratch

useState()

  • It allows us to add state to our function components.
  • useState returns for us two things:-
  • the actual value for the state
  • the state updater function for said state

Declare state variable with an initial value

  • The useState hook allows you set an initial value for every state you create. You can set this initial value by passing it as an argument to the useState hook when you declared it.
  • This initial value can be any valid data type in JavaScript. You can also leave the argument empty and create a state without any initial value.
  • In a class, we initialize the count state to 0 by setting this.state to {count: 0} in the constructor as shown below:
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  • But in the case of functional component, we have no this, so we canā€™t assign or read this.state . Instead, we call the useState Hook directly inside our component as shown below:
// Create function component:
function App() {
  // Declare new state without initial value:
  const [count, setCount] = useState()

  // Declare new state with string as initial value:
  const [word, setWord] = useState('Hello!')

  // Declare new state with number as initial value:
  const [num, setNum] = useState(0)

  // Declare new state with array as initial value:
  const [series, setSeries] = useState([0, 1, 2, 3])

  // Declare new state with object as initial value:
  const [person, setPerson] = useState({
    name: 'pankaj',
    email: 'pankaj@gmail.com'
  })

  return (
    <div>
      {/* ... */}
    </div>
  )
}

The names of state variables above can be anything you want, it doesn't matter for React. I personally advise using meaningful variable names depending on the state's purpose.

Now, could we use the initial value of state ??

  • When you want to read the state, access its value, you use the variable the hook returned.
  • Remember to use the state variable. Donā€™t try to use the update function to do this.

see the example below

// Create function component:
function App() {
  // Declare states for name and age:
  const [name, setName] = useState({
    firstName: 'Pankaj',
    lastName: 'Kumar'
  })
  const [age, setAge] = useState(21)

  return (
    <div>
      {/* Read from the "name" state. */}
      <p>Hello, my name is: {name.firstName} {name.lastName}</p>
      {/* Read from the "age" state. */}
      <p>My age is: {age}</p>
    </div>
  )
}

Update state variable

  • In a class, we need to call this.setState() to update the count state as shown below.
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
    Click me
  </button>
  • In the functional component, the simplest way to update the existing state is by using the update function returned for that state as shown below.
  function App() {
//declare count state
     const [count, setCount] = useState(0);

     return (
       <div>
         <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>
           Click me
         </button>
       </div>
     );
   }
  • In the above example, inside the App component, we declare a new state variable by calling useState Hook.
  • It returns a pair of values, to which we give names. Weā€™re calling our variable count because it holds the number of button clicks. We initialize it to zero by passing 0 as the only useState argument.
  • The second returned item is itself a function. It lets us update the count so weā€™ll name it setCount.
  • When the user clicks, we call setCount with a new value. React will then re-render the App component, passing the new count value to it.
Ā 
Share this