Essential React Custom Hooks 🪝

16/03/2025 Development 2 mins read
Table Of Contents

useLocalStorage

Save and retrieve values from localStorage with React state integration:

import { useState, useEffect } from 'react';
function useLocalStorage(key, initialValue) {
// Get stored value
const [storedValue, setStoredValue] = useState(() => {
if (typeof window === "undefined") return initialValue;
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
// Update stored value
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
if (typeof window !== "undefined") {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
}
// Usage
const [name, setName] = useLocalStorage('name', 'John');

useMediaQuery

Responsive design made easy:

import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
setMatches(media.matches);
const listener = (e) => setMatches(e.matches);
media.addEventListener('change', listener);
return () => media.removeEventListener('change', listener);
}, [query]);
return matches;
}
// Usage
const isMobile = useMediaQuery('(max-width: 768px)');

useFetch

Simplified data fetching:

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 isMounted = true;
const fetchData = async () => {
try {
const response = await fetch(url, options);
if (!response.ok) throw new Error(response.statusText);
const json = await response.json();
if (isMounted) {
setData(json);
setLoading(false);
}
} catch (error) {
if (isMounted) {
setError(error);
setLoading(false);
}
}
};
fetchData();
return () => { isMounted = false; };
}, [url, JSON.stringify(options)]);
return { data, loading, error };
}
// Usage
const { data, loading, error } = useFetch('https://api.example.com/data');