Creating Custom Hooks
Introduction
React Hooks enable state and lifecycle management in functional components. Custom Hooks allow developers to abstract and reuse logic, making code cleaner and more maintainable. This document details how to create and use custom Hooks with practical code examples.
Hooks Overview
React Hooks provide functional components with state and other React features. Common built-in Hooks include:
useState: Manages state.useEffect: Handles side effects.useContext: Accesses context.useReducer: Manages complex state logic.useMemo: Memoizes computed values.useCallback: Optimizes callback functions.
Custom Hooks Basics
A custom Hook is a function starting with “use” that can call other Hooks. It encapsulates complex logic, making component code clearer.
import { useState, useEffect } from 'react';
function useCustomHook() {
const [state, setState] = useState(initialState);
useEffect(() => {
// Handle side effects
return () => {
// Clean up side effects
};
}, []);
return [state, setState];
}Creating Basic Custom Hooks
Using useState
Create a simple custom Hook to manage a counter state.
// useCounter.js
import { useState } from 'react';
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
const reset = () => setCount(initialValue);
return { count, increment, decrement, reset };
}
export default useCounter;Using useEffect
Create a custom Hook to handle side effects, such as data fetching.
// useFetch.js
import { useState, useEffect } from 'react';
function useFetch(url, options = {}) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let ignore = false;
const fetchData = async () => {
try {
const response = await fetch(url, options);
if (!ignore && response.ok) {
const json = await response.json();
setData(json);
}
} catch (err) {
if (!ignore) {
setError(err);
}
} finally {
if (!ignore) {
setLoading(false);
}
}
};
fetchData();
return () => {
ignore = true;
};
}, [url, options]);
return { data, loading, error };
}
export default useFetch;Complex Custom Hooks
Combining Multiple Hooks
Custom Hooks can combine multiple built-in Hooks for advanced functionality.
// useAsync.js
import { useState, useEffect } from 'react';
function useAsync(asyncFunction, immediate = true) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [value, setValue] = useState(null);
useEffect(() => {
let didCancel = false;
const fetchData = async () => {
setLoading(true);
setError(null);
try {
const result = await asyncFunction();
if (!didCancel) {
setValue(result);
}
} catch (error) {
if (!didCancel) {
setError(error);
}
} finally {
if (!didCancel) {
setLoading(false);
}
}
};
if (immediate) {
fetchData();
}
return () => {
didCancel = true;
};
}, [asyncFunction, immediate]);
return { loading, error, value, execute: fetchData };
}
export default useAsync;Using useCallback and useMemo
Custom Hooks can use useCallback and useMemo to optimize performance and prevent unnecessary re-renders.
// useDebounce.js
import { useState, useCallback, useRef, useEffect } from 'react';
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
const timer = useRef(null);
useEffect(() => {
clearTimeout(timer.current);
timer.current = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(timer.current);
};
}, [value, delay]);
return debouncedValue;
}
export default useDebounce;Using Custom Hooks
Using custom Hooks in components simplifies logic and enhances clarity and maintainability.
// Counter.js
import React from 'react';
import useCounter from './useCounter';
function Counter() {
const { count, increment, decrement, reset } = useCounter(0);
return (
<div>
Count: {count}
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>Reset</button>
</div>
);
}
export default Counter;Advanced Custom Hooks
Using Generic Hooks
Generic Hooks enable reusable logic while maintaining type safety, such as a generic useAsync Hook for any asynchronous operation.
// useAsync.ts
import { useState, useEffect } from 'react';
type AsyncFunction<T> = (...args: any[]) => Promise<T>;
function useAsync<T>(asyncFunction: AsyncFunction<T>, immediate = true) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const [value, setValue] = useState<T | undefined>(undefined);
useEffect(() => {
let didCancel = false;
const fetchData = async (...args: Parameters<AsyncFunction<T>>) => {
setLoading(true);
setError(null);
try {
const result = await asyncFunction(...args);
if (!didCancel) {
setValue(result);
}
} catch (error) {
if (!didCancel) {
setError(error as Error);
}
} finally {
if (!didCancel) {
setLoading(false);
}
}
};
if (immediate) {
fetchData();
}
return () => {
didCancel = true;
};
}, [asyncFunction, immediate]);
return { loading, error, value, execute: fetchData };
}
export default useAsync;Creating Composable Hooks
Custom Hooks can be designed to be composable, facilitating the construction of complex logic.
// useDebounceEffect.js
import { useEffect, useRef } from 'react';
function useDebounceEffect(callback, dependencies, delay) {
const callbackRef = useRef(callback);
const timeoutId = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
useEffect(() => {
if (timeoutId.current) {
clearTimeout(timeoutId.current);
}
timeoutId.current = setTimeout(() => {
callbackRef.current();
}, delay);
return () => {
if (timeoutId.current) {
clearTimeout(timeoutId.current);
}
};
}, [delay, ...dependencies]);
}
export default useDebounceEffect;Using Custom Hooks for Form Management
Form management is a common requirement. A custom Hook can manage form state and handle input changes.
Form Custom Hook
import { useState } from 'react';
function useForm(initialValues) {
const [values, setValues] = useState(initialValues);
const handleChange = (event) => {
const { name, value } = event.target;
setValues({ ...values, [name]: value });
};
const resetForm = () => {
setValues(initialValues);
};
return { values, handleChange, resetForm };
}Using the Form Custom Hook
import React from 'react';
import useForm from './useForm';
function FormComponent() {
const { values, handleChange, resetForm } = useForm({ username: '', email: '' });
const handleSubmit = (event) => {
event.preventDefault();
console.log('Form submitted:', values);
resetForm();
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={values.username}
onChange={handleChange}
placeholder="Username"
/>
<input
type="email"
name="email"
value={values.email}
onChange={handleChange}
placeholder="Email"
/>
<button type="submit">Submit</button>
</form>
);
}Using Custom Hooks for API Requests
Handling API requests and state management is critical for web applications. A custom Hook can encapsulate API request logic.
API Request Custom Hook
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then((response) => response.json())
.then((data) => {
setData(data);
setLoading(false);
})
.catch((error) => {
setError(error);
setLoading(false);
});
}, [url]);
return { data, loading, error };
}Using the API Request Custom Hook
import React from 'react';
import useFetch from './useFetch';
function DataComponent() {
const { data, loading, error } = useFetch('https://api.example.com/data');
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h1>Data</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}Using Custom Hooks for Global State Management
Using Context and custom Hooks, you can create a simple global state management system.
Creating Context and Provider
import React, { createContext, useContext, useReducer } from 'react';
const GlobalStateContext = createContext();
const GlobalDispatchContext = createContext();
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
export function GlobalProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<GlobalStateContext.Provider value={state}>
<GlobalDispatchContext.Provider value={dispatch}>
{children}
</GlobalDispatchContext.Provider>
</GlobalStateContext.Provider>
);
}Creating Custom Hooks
export function useGlobalState() {
return useContext(GlobalStateContext);
}
export function useGlobalDispatch() {
return useContext(GlobalDispatchContext);
}Using Global State Custom Hooks
import React from 'react';
import { useGlobalState, useGlobalDispatch, GlobalProvider } from './GlobalState';
function Counter() {
const { count } = useGlobalState();
const dispatch = useGlobalDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
}
function App() {
return (
<GlobalProvider>
<Counter />
</GlobalProvider>
);
}
export default App;Using Custom Hooks for Subscriptions and Cleanup
When handling side effects, subscriptions and cleanup are common. Custom Hooks can encapsulate this logic.
Subscription and Cleanup Custom Hook
import { useState, useEffect } from 'react';
function useSubscription(source) {
const [data, setData] = useState(null);
useEffect(() => {
const subscription = source.subscribe((value) => {
setData(value);
});
return () => {
subscription.unsubscribe();
};
}, [source]);
return data;
}Using the Subscription and Cleanup Custom Hook
import React from 'react';
import { fromEvent } from 'rxjs';
import useSubscription from './useSubscription';
function MousePosition() {
const position = useSubscription(fromEvent(document, 'mousemove').pipe(
map(event => ({ x: event.clientX, y: event.clientY }))
));
return (
<div>
<p>Mouse Position: {position ? `(${position.x}, ${position.y})` : 'N/A'}</p>
</div>
);
}Error Boundaries in Hooks
Handling error boundaries in custom Hooks enhances application robustness and user experience, using try...catch to capture and manage errors.
// useFetch.js
import { useState, useEffect } from 'react';
function useFetch<T>(url: string, options?: RequestInit) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
let didCancel = false;
const fetchData = async () => {
try {
setLoading(true);
setError(null);
const response = await fetch(url, options);
if (!didCancel && response.ok) {
const json = await response.json();
setData(json);
}
} catch (error) {
if (!didCancel) {
setError(error as Error);
}
} finally {
if (!didCancel) {
setLoading(false);
}
}
};
fetchData();
return () => {
didCancel = true;
};
}, [url, options]);
return { data, loading, error };
}
export default useFetch;Testing Custom Hooks
Testing custom Hooks ensures their correctness and robustness. Use Jest and libraries like @testing-library/react-hooks to verify behavior under various conditions.
// useCounter.test.js
import { renderHook } from '@testing-library/react-hooks';
import useCounter from './useCounter';
describe('useCounter', () => {
it('increments the counter', () => {
const { result } = renderHook(() => useCounter());
const { increment } = result.current;
increment();
expect(result.current.count).toBe(1);
});
// Additional test cases...
});Sharing State Logic
State management is central to React applications, especially when multiple components need to share state. React offers several approaches, from simple Context to complex state management libraries like Redux and MobX.
Basic State Sharing: Props and Lifting Up State
Props
The simplest method is passing state as props from a parent to child components.
// Parent.js
import React, { useState } from 'react';
import Child from './Child';
function Parent() {
const [count, setCount] = useState(0);
return (
<div>
<Child count={count} />
</div>
);
}
export default Parent;
// Child.js
import React from 'react';
function Child({ count }) {
return <div>The count is: {count}</div>;
}
export default Child;Lifting Up State
When sibling components need shared state, lift the state to their common parent.
// SharedParent.js
import React, { useState } from 'react';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
function SharedParent() {
const [sharedState, setSharedState] = useState('');
return (
<div>
<ComponentA sharedState={sharedState} updateState={setSharedState} />
<ComponentB sharedState={sharedState} updateState={setSharedState} />
</div>
);
}
export default SharedParent;React Context API
The Context API enables data sharing across a component tree without manually passing props through every level.
Creating Context
// MyContext.js
import React from 'react';
const MyContext = React.createContext();
export default MyContext;Using Provider and Consumer
// App.js
import React from 'react';
import MyContext from './MyContext';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
function App() {
return (
<MyContext.Provider value={{ name: 'World' }}>
<ComponentA />
<ComponentB />
</MyContext.Provider>
);
}
export default App;
// ComponentA.js
import React from 'react';
import MyContext from './MyContext';
function ComponentA() {
const context = React.useContext(MyContext);
return <div>Hello {context.name}!</div>;
}
export default ComponentA;Redux
Redux is a popular state management library for large applications, providing a single global state tree and rules for state changes.
Creating the Store
// store.js
import { createStore } from 'redux';
const initialState = {
count: 0,
};
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
}
const store = createStore(reducer);
export default store;Using Provider and Connect
// App.js
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import ComponentA from './ComponentA';
function App() {
return (
<Provider store={store}>
<ComponentA />
</Provider>
);
}
export default App;
// ComponentA.js
import React from 'react';
import { connect } from 'react-redux';
function ComponentA(props) {
return <div>The count is: {props.count}</div>;
}
const mapStateToProps = state => ({
count: state.count,
});
export default connect(mapStateToProps)(ComponentA);MobX
MobX offers a simpler state management approach, automatically updating views via an observer pattern.
Creating the Store
// store.js
import { makeAutoObservable } from 'mobx';
class Store {
count = 0;
constructor() {
makeAutoObservable(this);
}
increment() {
this.count++;
}
decrement() {
this.count--;
}
}
export default new Store();Using Observer
// App.js
import React from 'react';
import { observer } from 'mobx-react-lite';
import store from './store';
function App() {
return (
<div>
<h1>The count is: {store.count}</h1>
<button onClick={() => store.increment()}>Increment</button>
<button onClick={() => store.decrement()}>Decrement</button>
</div>
);
}
export default observer(App);



