React hooks
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.
useState
We are already familiar with the useState
hooks function that was used to declare states. Let's create one more example of using the useState
hook. We will create a counter example that contains a button, and when it is pressed, the counter is increased by 1
, as illustrated in the following screenshot:
First, we create a Counter
component and declare a state called count
with the initial value 0
. The value of the counter state can be updated using the setCount
function. The code is illustrated in the following snippet:
import React, { useState } from 'react'; function Counter() { // count state with initial value 0 const [count...