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.
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:
- There's the current state, which we assigned in the preceding code to a constant called currentSwitchStatus.
- It has a function that must be used to update the state. In this example, we have assigned it to a constant called switchStatus.
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.
That's it—you're now hooked on hooks, right?
For reference, see the following: https://reactjs.org/docs/hooks-state.html.