๐ A Guide to React Custom Hooks
๐ก Newskategorie: Programmierung
๐ Quelle: dev.to
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.
ย
๐ Table of Contents
- Prerequisites
- Our First Custom Hook
- Tips for Building Custom Hooks
-
Sharing Logic with Custom Hooks
- Building a Data Fetching Hook
- Building a Form Handling Hook
- Wrapping Up
ย
Prerequisites
ย
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
.
ย
Our First Custom Hook
ย
Let's start by creating a simple custom Hook. Weโll build a useCounter
hook that encapsulates the logic for incrementing a counter.
import { useState } from 'react'
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue)
const increment = () => setCount(prevState => prevState + 1)
return [count, increment]
}
To use our useCounter
Hook, we can include it in a functional component:
import React from 'react';
import useCounter from './useCounter'
function CounterComponent() {
const [count, increment] = useCounter()
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
)
}
ย
Tips for Building Custom Hooks
ย
- Start by identifying repetitive logic across your components.
- Extract this logic into a function named with
use
prefix. Custom hooks should start withuse
, likeuseFormInput
oruseFetch
. - 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.
ย
Sharing Logic with Custom Hooks
ย
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.
ย
Building a Data Fetching Hook
ย
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
:
import { useState, useEffect } from 'react'
function useFetch(url) {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
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])
return { data, loading, error }
}
We can now use this Hook in our components to fetch data easily:
import React from 'react'
import useFetch from './useFetch'
function DataDisplayComponent({ url }) {
const { data, loading, error } = useFetch(url)
if (loading) return (
<p>Loading...</p>
)
if (error) return (
<p>Error: {error}</p>
)
return (
<div>
{JSON.stringify(data, null, 2)}
</div>
)
}
ย
Building a Form Handling Hook
ย
Handling forms in React can be verbose. A custom hook, useForm
, can simplify this. Hereโs how we might structure it:
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:
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.
ย
Wrapping Up
ย
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.
ย
...