React Hooks are special functions that allow functional components to use React features such as state, lifecycle methods, and context. Introduced in React 16.8, Hooks eliminate the need for class components while enabling cleaner and more reusable logic.
Hooks rely on the order in which they are called. React internally maps each Hook call to a stored state value based on call order, which is why breaking the rules leads to errors.
// Hooks must be called at the top level of the component
function Example() {
const [count, setCount] = React.useState(0);
const [name, setName] = React.useState("");
}
// Calling Hooks inside conditions breaks Hook order
function Example() {
if (true) {
const [count, setCount] = React.useState(0);
}
}
// Hooks are valid inside React function components
function App() {
const [count, setCount] = React.useState(0);
return <p>Count: {count}</p>;
}
// Hooks cannot be used inside normal JavaScript functions
function increment() {
const [count, setCount] = React.useState(0);
}
When Hooks are called conditionally or outside React components, React cannot correctly associate state with Hook calls. This leads to runtime errors and unpredictable behavior.
useuseStateuseEffect to update the document titleuseWindowSize