Hooks are a new feature in React that let you use state and other React features without writing a class. They were introduced in React 16.8 and have since become the preferred way to write React components.
Hooks are functions that "hook into" React state and lifecycle features from function components. They can be used to manage state, perform side effects, and access context.
To use a Hook, you simply call it inside a function component. Hooks can only be called at the top level of a component, not inside nested functions or loops. This helps to ensure that Hooks are used consistently and that their behavior is predictable.
Here is an example of how to use the useState
Hook to manage state in a function component:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Count: {count}</h1>
<button onClick={handleClick}>Increment</button>
</div>
);
}
export default Counter;
There are a few rules for using Hooks:
- Hooks can only be called inside React function components.
- Hooks can only be called at the top level of a component.
- Hooks cannot be conditional.
These rules help to ensure that Hooks are used consistently and that their behavior is predictable.