Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 14, 2021 07:58 am GMT

Let's break down the useState hook.

Hello Learners,

Today is the 2ndDay of #8DaysOfReactHook.
In This post will see the breakdown of the useState hook.

What is useState hook?

useState hook is a special function that lets us manage the state from the functional component.

Syntax of useState

image

let's see an example

image

let's break down the previous example

  • first, we have used the useState hook to define the state.
  • then we have displayed the state value using JSX.
  • on the button, we have added onClick so when we click the button count value will increment by 1.

How to set State based on Previous State value.

image

in the above example, we have created the clickHandler function and assigned it to the Button onClick.so, when the button is clicked the new count value will be set.

clickHandler function set the state value using the setCount function. but here we are setting a new state based on the previous state.

function return by useState hook takes a callback function with the previous state argument and based on that we can set a new value to the state.

useState with Object as the State value

image

above code shows the Object as the state value with useState hook.
when we use Object as a state value we need to use spread the value of state(...prevState) because the setState function doesn't persist the state value whenever it changes.

const prevState={ name:"", email:"[email protected]", password:""}const state={...prevState,[name]:"sachin"}so it will persist the value.

here we have used a controlled component by listening to the onChange handler.

useState with Array as the State value

The array is the heart of javascript and when it comes to React most of the time we work with Array.

Let me give you a better example:

let say we want to fetch articles from an Endpoint and store them into some variable so that we can render those articles to the webpage.
so, here we will use the Array as a state value and after fetching data we will store the articles to the Array.

now, if we want to render those articles we will use Array.map() method to do so.

If you have Doubt or Suggestions please let me know in the comment section.

Thank you for reading.


Original Link: https://dev.to/sachinchaurasiya/let-s-break-down-the-usestate-hook-c25

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To