Hooks are functions that let you use state and other React features without writing a class. Introduced in React 16.8, hooks provide a way to manage state and side effects in functional components, making your code more concise and easier to understand.
There are several built-in hooks in React, such as:
useState: For managing state.useEffect: For performing side effects like data fetching.useContext: For accessing context.useReducer: For managing complex state logic.useRef: For accessing DOM elements or keeping mutable values.Custom hooks allow you to encapsulate reusable logic and share it across multiple components. A custom hook is simply a JavaScript function whose name starts with "use" and that may call other hooks.
useState, useEffect, etc.Let's create a simple custom hook called useLocalStorage that helps manage state with localStorage.
// useLocalStorage.js
import { useState } from 'react';
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
}
export default useLocalStorage;
Now, let's use this custom hook in a component:
// App.js
import React from 'react';
import useLocalStorage from './useLocalStorage';
function App() {
const [name, setName] = useLocalStorage('name', 'Bob');
return (
<div>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<p>Hello, {name}!</p>
</div>
);
}
export default App;