Dennis Dang

October 16, 2024

Letter to developers writing React: PLEASE create custom hooks to encapsulate your logic.

Audience: developers that write React.js code.

If you have a large page component with many useState, useEffect, useWhatever, please remember you can create custom hooks that calls your individual hooks.

This is a component with poor encapsulation. All the innards (hooks) are spilled out onto the same local area.
```
function MyPage() {
     useState for this button
     useEffect for my button
     useCallback for my button

     useState for navbar
     useState for navbar filter
     useState for another navbar
}
```

Now try this. 
```
function MyPage() {
      const { ... } = useButton()
      const { ... } = useNavbar()
}

function useButton() {
     useState for this button
     useEffect for my button
     useCallback for my button

     return { all the states, handlers you want }
}

function useNavbar() {
     useState for navbar
     useState for navbar filter
     useState for another navbar

     return { all the states, handlers you want }
}

That's all. Now your code broken up and grouped into its nice little boxes.
```

What are the costs? 
1. A tiny bump on the call stack because we're creating a function. But you really shouldn't need to care about this.
2. The usual pains of React when you want to return references from your custom hooks that that end up in your dependency arrays. If you actually don't keep your references stable in your custom hooks, and some other hook uses it, you'll hit infinite renders.

Dennis