Introdution To useState Hooks in React

Introdution To useState Hooks in React

Prerequires:Basic knowledge of React and JavaScrict

What ia a Hook? A Hook is a special function that lets you “hook into” React features or a hook can also a special function that gives powers to functional components for a lifecycle as well as a state such as useEffect and useState hooks. But React hooks are now preferred for writing React components because they make the code shorter and easier to understand.

What is useState?

useState is a Hook that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.

You will rarely find React components written using class components nowadays.

What does the useState do in React?

As stated previously, useState enables you to add state to function components. calling React.useState inside a function component generates a single piece of state associated with that component.

Whereas the state in a class is always an object, with Hooks, the state can be any type. Each piece of state holds a single value, which can be an object, an array, a boolean, or any other type you can imagine.

So when should you use the useState Hook? It’s especially useful for local component state, but larger projects might require additional state management solutions.

Declaring state in React.

To declare state using React Hooks, we need to use the useState hook. The useState hook accepts a parameter which is the initial value of the state. In class-based components, state is always an object.

useState is a named export from react. To use it, you can write:

React.useState

Or to import it just write useState:

import React, { useState } from 'react';

But unlike the state object that you can declare in a class, which allows you to declare more than one state variable, like this:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

The useState Hook allows you to declare only one state variable (of any type) at a time, like this:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

In the example above, we are declaring the count variable and its update function setCount. It translates to this.state.count and this.setState in a class-based component. We pass 0 in useState as an argument, which initializes count to 0.

What does calling useState does?It declares a “state variable”. Our variable is called count but we could call it anything else, like car. This is a way to “save” some values between the function calls — useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React.

What do we pass to useState as an argument?The only argument to the useState() Hook is the initial state. Unlike with classes, the state doesn’t have to be an object. We can keep a number or a string if that’s all we need. In our example, we just want a number for how many times the user clicked, so pass 0 as initial state for our variable. (If we wanted to store two different values in state, we would call useState() twice.)

How many arguments are passed to useState?The argument initialState is passed on and used by useState >only once> during the initial render and any subsequent change to initialState not done by mutation at reference will not update the state value. However, if you mutate the initialState at its reference it might reflect in the state.

What does useState return?It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState(). This is similar to this.state.count and this.setState in a class, except you get them in a pair.

Now that we know what the useState Hook does, our example should make more sense:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

Note:

  • Always use the setState() method to change the state object, it will ensure that the component knows its been updated and calls the render() method (and all the other lifecycle methods).

  • We declare a state variable called count, and set it to 0. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current count, we can call setCount.

Updating State

In a class, we need to call this.setState() to update the count state:

<button onClick={() => this.setState({ count: this.state.count + 1 })}>
    Click me
  </button>

In a function, we already have setCount and count as variables so we don’t need this:

<button onClick={() => setCount(count + 1)}>
    Click me
  </button>

Run Down

Let’s now go over what we learned line by line and check our understanding.

1:  import React, { useState } from 'react';
 2:
 3:  function Example() {
 4:    const [count, setCount] = useState(0);
 5:
 6:    return (
 7:      <div>
 8:        <p>You clicked {count} times</p>
 9:        <button onClick={() => setCount(count + 1)}>
10:         Click me
11:        </button>
12:      </div>
13:    );
14:  }
  • Line 1: We import the useState Hook from React. It allows us keep local state in a function component.
  • Line 4: Inside the Example component, we declare a new state variable by calling the 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.
  • Line 9: When the user clicks, we call setCount with a new value. React will then re-render the Example component, passing the new count value to it.

This might seem like a lot to take in at first. Don’t rush it! If you’re lost in the explanation, look at the code above again and try to read it from top to bottom. We promise that once you try to “forget” how state works in classes, and look at this code with fresh eyes, it will make sense.

Conclusion

useState is a Hook (function) that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value. Ultimately, practising and building projects with this Hook will help anyone to pick it up faster.

Resources

Thank you for reading, don't forget to like and leave a comment.