DEV Community

loading...
Cover image for Let's break down the useState hook.

Let's break down the useState hook.

sachinchaurasiya profile image Sachin Chaurasiya Updated on ・2 min read

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:"sachinchaurasiyachotey87@gmail.com",
 password:""
}
const state={...prevState,[name]:"sachin"}

so it will persist the value.
Enter fullscreen mode Exit fullscreen mode

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.

Connect with me LinkedIn

Discussion (4)

Some comments have been hidden by the post's author - find out more

Forem Open with the Forem app