Defining state with the useState hook

The first React hook that we'll discover together is probably also the one that you'll use most: useState. As its name suggests, it enables function components to have/use internal state. React will maintain that internal state in-between the re-renders of the concerned components.

You can invoke the useState hook within a function component to define a single state variable, along with a function to update it.

You can also call useState multiple times in a single component to define multiple state variables.

Take a look at a simple example:

import React, {useState} from 'react'; 
 
export function Switch(props) { 
    const [currentSwitchStatus, switchStatus] = useState(false); 
 
    return ( 
        <div> 
            <span>The switch is currently: {currentSwitchStatus? 'ON': 
'OFF'}
</span> <button onClick={() =>
switchStatus(!currentSwitchStatus)}
>Change the value!
</button> </div> ); }

Here, we have created a Switch component. By default, the switch is disabled, but we can change its state by clicking on the button.

The most important line is this one: const [currentSwitchStatus, switchStatus] = useState(false);.

The value that we pass to the useState function (that is, to the hook) is the initial value for our new state variable.

The useState function returns a tuple composed of the following:

The [ ] characters around our constants are an ES2015 feature called array destructuring. We'll explain how it works in the next section.

In the JSX code of the component, we have simply used the current state constant to display either ON or OFF. Finally, in the onClick event handler of the button, we called the state update function to switch the value.

The state update function does not merge the new value into the previous one; it simply replaces it. Again, immutability is favored and that's a good thing!

That's it—you're now hooked on hooks, right?

For reference, see the following: https://reactjs.org/docs/hooks-state.html.