Create Your Own Custom Hook in React
Hello, fellow developers! 🌟 Today, we’re going to dive into the world of custom hooks in React. If you’re new to React or just starting to dip your toes into the rich world of hooks, you’re in the right place. Hooks were introduced to allow state and other React features to be used without writing a class. Custom hooks take these built-in hooks and let you compose behavior and logic into reusable pieces. Let’s explore how we can create a custom hook step-by-step!
What are Custom Hooks?
Before we jump into coding, let’s understand what custom hooks are. In React, custom hooks are a way to reuse logic among components. They allow us to extract component logic into reusable functions. If you find yourself using the same logic in multiple components, that’s a great candidate to become a custom hook.
Why Use Custom Hooks?
Here’s why you might want to use custom hooks:
– Reusability: Extract similar logic and use it across components.
– Readability: Encapsulate complex logic, making components neat and tidy.
– Testing: Make it easier to test isolated hooks instead of entire components.
Now that we have a basic understanding, let’s create a simple custom hook!
Let’s Create a Custom Hook: useLocalStorage
We’ll create a custom hook named useLocalStorage. This hook will help us manage localStorage within our React application with ease. It will work similarly to the useState hook but will read/write data to the browser’s localStorage.
Step 1: Set Up a New React App
First things first, fire up your terminal and create a new React app using Create React App.
bash
npx create-react-app custom-hooks-example
cd custom-hooks-example
npm start
You should see your app running at http://localhost:3000.
Step 2: Create Your Custom Hook
Navigate to your src directory and create a new file useLocalStorage.js:
javascript
// useLocalStorage.js
import { useState } from 'react';
function useLocalStorage(key, initialValue) {
// Retrieve an item from local storage
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error("Error reading from localStorage", error);
return initialValue;
}
});
// Define a function to store a new value
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error("Error setting localStorage key", error);
}
};
return [storedValue, setValue];
}
export default useLocalStorage;
The hook consists of two main parts:
– State Management: Using useState, we load data from localStorage when the component mounts.
– Persisting Data: The setValue function updates both the state variable and localStorage.
Step 3: Use the Custom Hook in Your Component
Now that we have our custom hook, let’s use it inside a component!
javascript
// App.js
import React from 'react';
import useLocalStorage from './useLocalStorage';
function App() {
const [name, setName] = useLocalStorage('name', 'Guest');
return (
Welcome, {name}!
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
);
}
export default App;
Step 4: Test It Out!
Open your app in the browser. Type a name into the input box and refresh the page. Notice how the name persists? 🧙‍♂️ That’s the power of localStorage at work using a custom hook! It’s magically simple.
Custom Hook Best Practices
Here are some tips to consider when creating custom hooks:
– Prefix with “use”: Always start the hook name with “use”. This convention tells React that the rule-of-hooks applies.
– Simplification: Extract only stateful logic into hooks; avoid encapsulating entire behavior, which may decrease clarity.
– Document: Even though it’s reusable, document its behavior and share any nuances with your team.
Conclusion
And there you have it! You’ve successfully created your first custom React hook. Custom hooks are a powerful way to share logic across components, keeping your codebase DRY (Don’t Repeat Yourself) and organized.
Practice Ideas
– Try creating a useWindowSize hook to track and use the window’s dimensions.
– Build a useFetch hook to handle data fetching and state management.
– Share your custom hooks with your peers and see if they have any suggestions or improvements.
Remember, the best way to learn is by doing, so keep experimenting and crafting your hooks! If you have any questions, feel free to reach out to me. Happy coding, and I hope to see you again on sagarkunwar.com.np! 🎉
