20 December 2022
React hooks let you use state and other React features without writing class components. Since their introduction in React 16.8, they have become the standard way to write functional components.
Using hooks offers several advantages:
- They let you manage state and lifecycle features inside functional components, making your code cleaner and more concise. You no longer need to worry about binding event handlers or translating lifecycle methods to classes.
- They make it easy to extract stateful logic from a component and reuse it elsewhere, which leads to highly modular and testable code.
- They can help optimize performance. For instance, hooks like `useMemo` let you cache expensive calculations so they only run when their inputs change.
Modern React applications rely heavily on hooks. Here are some of the most common hooks you will work with:
> 💡 **Want a quick reference?** Check out our complete, interactive **[React Hooks Cheatsheet](/cheatsheets/react-hooks/)** with comprehensive usage guidelines, examples, and rules for all built-in React hooks.
## 1. useState()
`useState()` is the go-to hook for adding state to functional components. It returns an array with two elements: the current state value and a function to update it.
```jsx
import { useState } from "react";
function Example() {
const [count, setCount] = useState(0);
return (
You clicked {count} times
You clicked {count} times
Hello, world!
;
}
```
In this example, `useLayoutEffect()` logs the width of the div element synchronously. Because it runs before the browser repaints the screen, any updates you make based on that measurement will render seamlessly.
## 5. useReducer()
`useReducer()` is an alternative to `useState()` for managing complex state logic, especially when the next state depends on the previous one, or when you have multiple sub-values. It uses a reducer function similar to what you might find in Redux.
```jsx
import { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
throw new Error();
}
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
The count is {state.count}