React Hooks Overview

AkashSDas
3 min readMar 29, 2024

--

Hooks are one of the most crucial parts of React. Understanding them, their benefits and caveats will help us to craft better solutions.

Hooks allow us to use features of React in our function components (only). They were introduced in React v16.8. React provides some built-in hooks for base usage, and they can be composed into custom hooks too.

Built-in Hooks in React

Prior to hooks, we had to use class components to use React features, and sharing any logic was very difficult and required use of patterns like Higher Order Components and Render Props which made the component tree more complex and harder to debug.

Knowing all of the hooks is not worth the time as most of the time we’ll be using useState, useReducer, useEffect, useRef, useMemo, useCallback, and useContext, and sometimes useDebugValue. Some of the hooks like use and useOptimistic as of today are experimental.

There’re some important things to remember while working with hooks:

  • Their name starts with use (even for custom hooks)
  • They should be defined at the top of the component
  • They can’t be used inside if-else or loops

Custom Hooks

Due to the composable nature of React Hooks, we can create our own custom hook which will have our logic. Its going to be a function whose name starts with use.

Consider the following example where we’ve useCounter hook that encapsulates counter logic and only exposes the count reactive value and method to increment the counter.

import { useState } from "react";

function useCounter() {
const [count, setCount] = useState(0);

function increment(): void {
setCount((prevCount) => prevCount + 1);
}

return { count, increment };
}

export default function App(): JSX.Element {
const { count: count1, increment: increment1 } = useCounter();
const { count: count2, increment: increment2 } = useCounter();

return (
<section>
<div>
<h1>Counter 1: {count1}</h1>
<button onClick={increment1}>Increment</button>
</div>

<div>
<h1>Counter 2: {count2}</h1>
<button onClick={increment2}>Increment</button>
</div>
</section>
);
}

In the above example, we call the useCounter hook twice. Each call creates an independent counter and increment method. Therefore, when we increment counter 1, only counter 1 increases with +1 and counter 2 remains unchanged. This is an important feature of using custom hook and we should take care of, other bugs will be introduced.

Built-in Hooks

You can read regarding the built-in hook in the following articles:

1. State

2. Effect

3. Performance

4. Ref

5. Other Hooks

--

--