DEV Community

loading...

Use State in functional component of React

a26230203 profile image Bin ・1 min read

Alt Text

Introduction

This post to understand how to use state in functional component of React. As we know React has functional and class components and we usually using the Class Components whenever we require to use state of components:
Alt Text
But we also able to use React Hooks to add state into Functional components

React.useState Hook

The function of useState is hook that allow you add and maintain state within the Functional components. First of all, you need to import useState from React
Alt Text

Then here we have dog as state variable and setDog as the function to update the dog. The useState Hook only allow one state variable being declare at once, in other words if you have multiple state, you should create multiple variables.

Alt Text

Update state

Like we using setState in Class components, we are going to use setDog in Functional components to updated the value of dog

Alt Text

References:

https://reactjs.org/docs/hooks-intro.html

Discussion (0)

Forem Open with the Forem app