DEV Community

loading...
Cover image for useState - React Hooks Series

useState - React Hooks Series

Pratap Sharma
I'm a self-taught Full Stack Software Developer, Technical Writer, and React/React-Native Trainer.
Originally published at pratapsharma.in Updated on ・2 min read

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";
Enter fullscreen mode Exit fullscreen mode
  1. How to use:
const [name, setName] = useState("Pratap");
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (2)

Collapse
chetan_atrawalkar profile image
Chetan Atrawalkar👉CA.

Helpful Series 👍

Collapse
quocbahuynh profile image
Huỳnh Bá Quốc

Tks bro