Mid From PDF React React.js

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.

More from React.js Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details