DEV Community

Cover image for What s useState?
Ivan García
Ivan García

Posted on

What s useState?

well is a hook. Which in other words, is a function, which is imported from react

import { useState } from 'react' 
Enter fullscreen mode Exit fullscreen mode

but which is your function?

Help us to controller a state, recive a first param which is the initial state

useState(initialState)
Enter fullscreen mode Exit fullscreen mode

But what a the initial state?
It is the value which initiates our state

For example:

 A object useState({}) or Array useState([]) 
 A string useState('whil')
 A number useState(5)
 A Boolean useState(true) 
Enter fullscreen mode Exit fullscreen mode

every time our functional component Renders. Begins with the initial state

But what a return?
Returns us two values. Which is a current state and a function for update

const [state, setState] = useState(false)
Enter fullscreen mode Exit fullscreen mode

But which is our current state?

Well is our initial state which is your current state. Why?
Remember that Provide a initial state. That initial state is our current state during the first rendering

How update our current state?

Remember that useState return a function which we can update the current state

setState
Enter fullscreen mode Exit fullscreen mode

the shape for update our current value is like that.

const handleState = () =>{
  setState(true)
} 
Or
JSX. 
Return(
   <button onClick={() =>setState(true)} > Click Me </button>
) 
Enter fullscreen mode Exit fullscreen mode

because is not called createState?

Because it wouldn't be right. Because the state Only Be create one-time when our functional component Be render for first time

setState is not function async. Just calling to enqueueState or enqueueCallback when update and your execution feels how If it were async

Top comments (0)