Featured
Designing Custom Hooks in React
What are Hooks in React?
Custom functions that allow you to access React functionality like useState and useEffect outside of component files. These isolated custom functions can then be imported into regular React component files.
Why use Hooks?
First, they eliminate bloat from your component files by moving the code above the return statement into another file. Second, you are following the re-usable component React philosophy by being able to re-use that functionality in any component. Third, your React project will be easier to maintain since there is one one source of truth for that functionality tucked away into its own hook.
General Hook Design
Before getting into any specfics, it is recommended to let hooks happen naturally, i.e. don't begin by making them. As your project grows naturally, you'll notice certain repetitions in different components that you can then extract into their own hooks.
1. Find code related to a single piece of state in a component
2. Create a new file at `hooks/use-something.js`
3. Define a new function called useSomething and move that code into there
4. Remove all JSX and references to unneeded variables
5. This hook will return an object with things a component will need
6. Component will import this hook and destructure the values it needs at above the return statement
Practical Applied Example
We have a counter page in our React app that has a counter number showing and a button underneath it. Everytime the button is clicked, the counter number is increased by one. Lastly, on every click, the value of the counter is also being logged on every click and this is being handled from a useEffect which executes again once the counter value changes.
Thus we have: 1) the counter state variable 2) the handler function that modifies it 3) the useEffect functionality
We will separate these three things from our counter page and move it to `hooks/use-counter.js` and paste it within the body of a new function called `useCounter`
Next we need to import useState and useEffect hooks from React so we can use them in this new file.
Once everything is adjusted, we return an object containing the counter state value and the handler function that updates it. (the use effect functionality stays in the hook)
Back in the counter page, we import our new hook and use the stuff in the JSX
```jsx
import useCounter from '../hooks/use-counter'
function CounterPage() {
// counter = counter state variable
// increment = setCounter(counter + 1)
const [counter, increment] = useCounter()
return (
<div>
<h1>Counter is {counter}</h1>
<button onClick={increment}>Increase Counter </button>
</div>
)
}
```
Look at how clean the component is!
Comments
Post a Comment