Hooks were introduced in React version 16.8. Hooks allow you to use state and some other React features in functional components. Before hooks, you had to write class components if states or complex component logic were needed.
There are certain important rules for using hooks in React. You should always call hooks at the top level in your React function component. You shouldn’t call hooks inside loops, conditional statements, or nested functions. Hook names begin with the word
use, followed by the purpose they serve.
We are already familiar with the
useState hook function that is used to declare states. Let’s look at one more example of using the
useState hook. We will create an example counter that contains a button, and when it is pressed, the counter is increased by
1, as illustrated in the following screenshot:
Figure 8.6: Counter component
- First, we create a
Countercomponent and declare a state called