In React, custom Hooks are a mechanism for reusing state logic, allowing you to share logic between components without writing classes. Creating custom Hooks is typically done to solve specific problems or encapsulate complex logic, making it easy to share these logics across multiple components.
Creating Custom Hooks:
-
Naming Custom Hooks must start with
use, which is the indicator for React to recognize custom Hooks. For example,useLocalStorageoruseFormInput. -
Writing the Hook Function Custom Hooks are essentially JavaScript functions. This function can call other Hooks (such as
useStateoruseEffect) and include additional logic. -
Returning Necessary Values Depending on your needs, custom Hooks can return any necessary values. These values can be data, functions, or any other type to be used within components.
Example:
Suppose we need a custom Hook to handle read and write operations for LocalStorage. We can create a Hook named useLocalStorage:
javascriptimport { useState } from 'react'; function useLocalStorage(key, initialValue) { // Retrieve the stored value from localStorage; use initialValue if not present const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.log(error); return initialValue; } }); // Set the value in localStorage 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]; }
Using Custom Hooks:
In your component, you can use useLocalStorage just like any other Hook:
javascriptfunction App() { const [name, setName] = useLocalStorage('name', 'Bob'); return ( <div> <input type="text" value={name} onChange={e => setName(e.target.value)} /> </div> ); }
The above example demonstrates how to create and use a simple custom Hook for interacting with LocalStorage. By doing this, you can encapsulate complex or commonly used logic within Hooks and reuse them across multiple components. This not only makes the code cleaner and better organized but also enhances maintainability and testability.