A Guide to React Custom Hooks
Tags: react, hook, javascript, webdev
Published: 2023-11-18 17:57:58

Custom Hooks in React are a powerful feature that allows us to extract component logic into reusable functions. These Hooks are JavaScript functions that can use other Hooks provided by React. They enable us to organize logic into separate, reusable modules.


&nbsp;

📌 **Table of Contents**

- [Prerequisites](#prerequisites)
- [Our First Custom Hook](#our-first-custom-hook)
- [Tips for Building Custom Hooks](#tips-for-building-custom-hooks)
- [Sharing Logic with Custom Hooks](#sharing-logic-with-custom-hooks)
  - [Building a Data Fetching Hook](#building-a-data-fetching-hook)
  - [Building a Form Handling Hook](#building-a-form-handling-hook)
- [Wrapping Up](#wrapping-up)


&nbsp;

## Prerequisites

&nbsp;

Before diving into custom Hooks, it's important to have a basic understanding of React and its core concepts, such as components, state, and built-in Hooks like `useState` and `useEffect`.


&nbsp;

## Our First Custom Hook

&nbsp;

Let's start by creating a simple custom Hook. We’ll build a `useCounter` hook that encapsulates the logic for incrementing a counter.

```jsx
import { useState } from 'react'

// Custom hook for counter functionality
function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue) // State to keep track of count

  // Function to increment count
  const increment = () => setCount(prevState => prevState + 1)

  // Returns count and increment function
  return [count, increment]
}

```

To use our `useCounter` Hook, we can include it in a functional component:

```jsx
import React from 'react';
import useCounter from './useCounter'

// Component using the useCounter Hook
function CounterComponent() {
  const [count, increment] = useCounter() // Utilizing useCounter

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  )
}
```

&nbsp;

## Tips for Building Custom Hooks

&nbsp;

- Start by identifying repetitive logic across your components.
- Extract this logic into a function named with `use` prefix. Custom hooks should start with **`use`**, like **`useFormInput`** or **`useFetch`**.
- Use React's built-in Hooks within your custom Hook as needed.
- Return anything that will be useful for the component using this Hook.
- Each custom hook should be responsible for a single piece of functionality.

&nbsp;

## Sharing Logic with Custom Hooks

&nbsp;

Custom Hooks are excellent for sharing logic across multiple components. In this section, we will create two common custom hooks that React developers often create to share logic across multiple components.

&nbsp;

### Building a Data Fetching Hook

&nbsp;

 If we need to fetch data from an API in several components, we can create a `useFetch` Hook. Here's a simple implementation of `useFetch`:

```jsx
import { useState, useEffect } from 'react'

// Custom hook for fetching data
function useFetch(url) {

  const [data, setData] = useState(null) // State for data
  const [loading, setLoading] = useState(true) // State for loading
  const [error, setError] = useState(null) // State for error handling

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true)
      setError(null)

      try {
        const response = await fetch(url)

        if (!response.ok) {
          throw new Error(`An error occurred: ${response.statusText}`)
        }

        const jsonData = await response.json()
        setData(jsonData)
      } catch (error) {
        setError(error.message)
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [url]) // Dependency array with url

  return { data, loading, error }
}
```

We can now use this Hook in our components to fetch data easily:

```jsx
import React from 'react'
import useFetch from './useFetch'

// Component using the useFetch Hook
function DataDisplayComponent({ url }) {
  const { data, loading, error } = useFetch(url) // Utilizing useFetch

  if (loading) return <p>Loading...</p>
  if (error) return <p>Error: {error}</p>

  return <div>{JSON.stringify(data, null, 2)}</div>
}
```

&nbsp;

### Building a Form Handling Hook

&nbsp;

Handling forms in React can be verbose. A custom hook, **`useForm`**, can simplify this. Here’s how we might structure it:

```jsx
import { useState } from 'react'

function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue)

  const handleChange = (e) => {
    setValue(e.target.value)
  }

  // Returns an object with value and onChange properties
  return {
    value,
    onChange: handleChange
  }
}
```

We can now use this Hook in our form related components:

```jsx
import React from 'react'
import useFormInput from './useFormInput'

function FormComponent() {

  const name = useFormInput('')
  const age = useFormInput('')

  const handleSubmit = (e) => {
    e.preventDefault()
    console.log(`Name: ${name.value}, Age: ${age.value}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>
          Name:
          {/* The spread operator here is equivalent to value={name.value} onChange={name.onChange} */}
          <input type="text" {...name} />
        </label>
      </div>
      <div>
        <label>
          Age:
          <input type="number" {...age} />
        </label>
      </div>
      <button type="submit">Submit</button>
    </form>
  )
}
```

> 💡 The implementation of `useFormInput` provided here is a basic version, designed for straightforward form input management. If additional functionalities are required, such as form validation or handling more complex form patterns, the Hook should be further customized and extended.
> 


&nbsp;

## Wrapping Up

&nbsp;

Custom Hooks in React offer a powerful and elegant way to reuse and share logic across components. By understanding and leveraging this feature, we can significantly simplify our components and improve our code's maintainability and readability.


&nbsp;

![rich-text-editor-for-react npm package](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/scz09ynfwbdvqflj9ssh.png)
>[Demo](https://rich-text-editor-for-react.rasaf-ibrahim.com) | [Documentation](https://docs.rich-text-editor-for-react.rasaf-ibrahim.com)