useState - React Hooks Series

useState Banner

Welcome to the hooks series of react. In this series, I will go through the different hooks which were introduced in React 16.8.

Series path

Why do we prefer functional component over class component in react

  1. Functional component is much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks
  2. Functional component are written shorter and more straightforward, which makes it easier to develop, understand, and test.
  3. With the introduction of Hooks in we are now able to manage state in functional components.

What is Hooks?

Hooks were a new addition in React 16.8. They let you use state and other React features without writing a class. It means you don't need to use a class component to use a state.

What is useState Hook?

useState is a Hook which allows you to have state variables in functional components.

  1. First of all, let us import useState hook from react.
import React, { useState } from "react";
  1. How to use:
const [name, setName] = useState("Pratap");

Let us try to understand what we just added:

  • name: State Variable.
  • setName: Function to change the state value.
  • useState: useState react Hook.
  • Pratap: State initial value.

Example

import React, { useState } from "react";

const Example = () => {
  const [name, setName] = useState("Pratap");

  return (
    <div>
      <h1>{name}</h1>
    </div>
  );
};

export default Example;

Now, let us add a button which will change the state value from Pratap to Prasar.

import React, { useState } from "react";

const Example = () => {
  const [name, setName] = useState("Pratap");

  const changeState = () => {
    //This will change the state value
    setName("Prasar");
  };

  return (
    <div>
      <h1>{name}</h1>
      <button onClick={changeState}>Change Name</button>
    </div>
  );
};

export default Example;

Code Sandbox Sample

Here is the example of the above blog. Feel free to play with it.

Conclusion

In the next article in this React Hooks series, we will get to know and see about useEffect hooks.

Thank you for reading my first part in the React Hooks Series!

Series path

💌 If you'd like to receive more tutorials in your inbox, you can sign up for the newsletter here.

Discussions

Up next