Lesson 1. Store a local state with useState 1. Creating and updating a local state
Let’s consider this component, containing a text input. Here we want to keep, as a local state, the value entered in the input and display it below the input:
Result
useState
takes as a parameter the initial value of your state and returns an array with two elements: the current value of the state and a function to set the state's new value.- To get the state's current value, use the first value returned by
useState
, herename
. - To update the state's value, call the function returned as second value by
useState
, heresetName
, with, as a parameter, the new value.
Updating the state
When a component defines a local state, the only way to update it is to use the
setter returned as the second element by the call to useState
.
This means that the following snippets are incorrect:
const [value, setValue] = useState(0)value = 1
const [object, setObject] = useState({ key: 'aaa', value: 1 })object.value = 1
const [array, setArray] = useState([1, 2, 3])array.push(4)
If you incorrectly update the state, you won’t get any error, but some weird behaviors will happen. For instance, the component will not re-render, and you will not see your updates in the browser.
This is why it can be very useful to be used to the spread syntax to create new arrays and objects from existing ones:
setValue(1)setObject({ ...object, value: 1 })setArray([...array, 4])
Exercise
Can you update this component so when the user clicks the button:
- it adds the value of the input to the list, and
- it clears the input?
Result
Click here to see the solution!
To update the tasks
state, we can use the spread operator (...
) to create a
new array from the existing one tasks
, and call setTasks
with this new
array:
<buttononClick={() => {setTasks([...tasks, newTask])setNewTask('')}}>Add</button>