useState

    The useState hook lets us "remember" a value within a component function. Since our component function may be called many times throughout the lifecycle of the component, any variable we declare normally (i.e. with let myVar = ...) will get reset. With useState, React can remember a state variable for us, making sure it gets passed into our component instance correctly.

    API

    The useState hook takes a single argument, our initial state, and returns an array containing two elements:

    • state - the current state
    • setState - a function to update our state

    E.g. const [state, setState] = useState(initialValue)

    Example

    In this example, we'll use useState to append to an array.

    The useState hook can store any type of value: a number, a string, an array, an object, etc. We've previously used useState to increment a number value and change a string.

    Awesome! We start with an initial state of [1, 2, 3], and when we click "roll dice", we see new values appended to the list.

    Note how when we call setDiceRoll, we're not pushing the integer returned from randomDiceRoll() into the diceRolls array. Instead, we return a new array containing the destructured diceRolls array and the newly randomized dice roll. Why?

    Hooks can tell React to re-run our component function and update the UI. The useState hook tells React to re-run our component function whenever we call setDiceRolls with a different value. Internally, useState then compares the current value of diceRolls with the value we passed to setDiceRolls using ===. If we're using a mutable value like an array, and we only change its contents, useState won't detect that change and won't tell React to re-run our component function. This will result in our UI displaying old/stale data. To avoid this problem we need to create a new array, so that useState will detect that our data changed and display the newest data.

    Contents
    1. API
    2. Example