How do you share logic between components with custom hooks?
Custom hooks are a powerful way to share logic between components in a reusable and
encapsulated way. A custom hook is simply a JavaScript function that uses React hooks
(like useState, useEffect, etc.).
Example of a custom hook:
// useLocalStorage.js
import { useState } from 'react';
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
const setValue = (value) => {
setStoredValue(value);
localStorage.setItem(key, JSON.stringify(value));
};
return [storedValue, setValue];
}
export default useLocalStorage;
You can then use this custom hook in any component:
import useLocalStorage from './useLocalStorage';
function App() {
const [name, setName] = useLocalStorage('name', 'John');
return (
<div>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
</div>
);
}
Custom hooks allow for reusable logic (like managing form state, fetching data, etc.) and
encapsulation of behavior in a way that doesn't require repeated code.