useState
The React useState Hook allows us to track state in a function component.
State generally refers to data or properties that need to be tracking in an application.
import { useState } from "react"
useState accepts an initial state and returns two values:
- The current state.
- A function that updates the state.
import { useState } from "react";
const FavoriteColor = () => {
const [color, setColor] = useState("")
setColor("#F00")
}
Notice that again, we are destructuring the returned values from useState.
The first value, color, is our current state.
The second value, setColor, is the function that is used to update our state.
Example usage
import { useState } from 'react'
const App = () => {
const [color, setColor] = useState('#F00');
return (
<>
<h1 style={{ color: color }}>
My favorite color is { color }!
</h1>
<button
type="button"
onClick={() => setColor('#00F')}
>Set to blue!
</button>
</>
)
}
export default App
The useState Hook can be used to keep track of
strings, numbers, booleans, arrays, objects, and any combination of these!
We could create multiple state Hooks to track individual values.
Example with objects
Let's update an object:
import { useState } from 'react'
const App = () => {
const person = {
id: 1,
firstname: "John",
lastname: "Doe",
job: "Developer"
}
const [employee, setEmployee] = useState(person);
const updateEmployee = (params) => {
setEmployee(params)
console.log(employee)
}
return (
<>
<h1>{ `${employee.firstname} ${employee.lastname}` }</h1>
<button
type="button"
onClick={() => updateEmployee({ firstname: "Bob"}) }
>Set firstname to Bob!
</button>
</>
)
}
export default App
:::info Questions
-
Why is the first
console.logresult:{id: 1, firstname: "John", lastname: "Doe", job: "Developer"} -
and after another click on the button:
{firstname: "Bob"} -
What happened to the rest of the object? :::
Let's fix this:
By destructuring the arguments and utilizing the JavaScript spread operator, we can fix this issue!
const updateEmployee = ({firstname}) => {
setEmployee(prev => ({ ...prev, firstname }) )
console.log(employee)
}