Environment friendly, Cleaner, and Reusable Code with Customized React Hooks

[ad_1]

Christina Morillo

Now that you just’re comfy making a customized hook, let’s take it up a notch. We’ll discover ten sensible examples of customized hooks you can begin utilizing in your tasks at the moment. Let’s dive in!

useLocalStorage

useLocalStorage is a customized hook that simplifies using native storage in your React apps. It permits you to learn, write, and take away knowledge from the native storage.

operate useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
attempt {
const merchandise = window.localStorage.getItem(key);
return merchandise ? JSON.parse(merchandise) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});

const setValue = worth => {
attempt {
const valueToStore = worth instanceof Operate ? worth(storedValue) : worth;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
};

return [storedValue, setValue];
}

useDocumentTitle

useDocumentTitle is a customized hook that makes it simple to vary the doc title from a React part.

operate useDocumentTitle(title) {
useEffect(() => {
doc.title = title;
}, Environment friendly, Cleaner, and Reusable Code with Customized React Hooks);
}

useEventListener

useEventListener is a customized hook that makes it easy so as to add occasion listeners to any DOM factor.

operate useEventListener(eventName, handler, factor = window) {
useEffect(() => {
const isSupported = factor && factor.addEventListener;
if (!isSupported) return;

factor.addEventListener(eventName, handler);

return () => {
factor.removeEventListener(eventName, handler);
};
}, [eventName, element, handler]);
}

useOnClickOutside

useOnClickOutside is a customized hook that fires an occasion when a consumer clicks exterior a selected part. It is useful for issues like closing dropdown menus.

operate useOnClickOutside(ref, handler) {
useEffect(() => {
const listener = occasion => ref.present.accommodates(occasion.goal)) return;
handler(occasion);
;
doc.addEventListener("mousedown", listener);
doc.addEventListener("touchstart", listener);
return () => {
doc.removeEventListener("mousedown", listener);
doc.removeEventListener("touchstart", listener);
};
}, [ref, handler]);
}

useHover

useHover is a customized hook that detects whether or not your mouse is hovering over a component.

operate useHover() {
const [value, setValue] = useState(false);

const ref = useRef(null);

const handleMouseOver = () => setValue(true);
const handleMouseOut = () => setValue(false);

useEffect(
() => {
const node = ref.present;
if (node) {
node.addEventListener('mouseover', handleMouseOver);
node.addEventListener('mouseout', handleMouseOut);

return () => {
node.removeEventListener('mouseover', handleMouseOver);
node.removeEventListener('mouseout', handleMouseOut);
};
}
},
[ref] // Recall provided that ref modifications
);

return [ref, value];
}

useOnlineStatus

useOnlineStatus is a customized hook that detects whether or not the consumer is at present on-line or offline.

operate useOnlineStatus() {
const [isOnline, setOnline] = useState(navigator.onLine);

const goOnline = () => setOnline(true);
const goOffline = () => setOnline(false);

useEffect(() => {
window.addEventListener('on-line', goOnline);
window.addEventListener('offline', goOffline);

return () => {
window.removeEventListener('on-line', goOnline);
window.removeEventListener('offline', goOffline);
};
}, []);

return isOnline;
}

useWindowSize

useWindowSize is a customized hook that permits you to entry the present window measurement.

operate useWindowSize() {
const [size, setSize] = useState([window.innerWidth, window.innerHeight]);

useLayoutEffect(() => {
const updateSize = () => {
setSize([window.innerWidth, window.innerHeight]);
};
window.addEventListener('resize', updateSize);
updateSize();

return () => window.removeEventListener('resize', updateSize);
}, []);

return measurement;
}

useMediaQuery

useMediaQuery is a customized hook that permits you to use media queries in your parts.

operate useMediaQuery(question) {
const [matches, setMatches] = useState(window.matchMedia(question).matches);

useEffect(() => {
const mediaQueryList = window.matchMedia(question);
const documentChangeHandler = () => setMatches(mediaQueryList.matches);

mediaQueryList.addListener(documentChangeHandler);
documentChangeHandler();
return () => {
mediaQueryList.removeListener(documentChangeHandler);
};
}, [query]);

return matches;
}

useDebounce

useDebounce is a customized hook that helps to delay a operate name and debounce the given worth.

operate useDebounce(worth, delay) {
const [debouncedValue, setDebouncedValue] = useState(worth);

useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(worth);
}, delay);

return () => {
clearTimeout(handler);
};
}, [value, delay]);

return debouncedValue;
}

useInterval

useInterval is a customized hook that permits you to arrange a recurring operate name with a specified interval. It is helpful when it’s worthwhile to execute a operate repeatedly, like updating a timer or polling a server.

operate useInterval(callback, delay) {
const savedCallback = useRef();

// Bear in mind the most recent callback.
useEffect(() => {
savedCallback.present = callback;
}, [callback]);

// Arrange the interval.
useEffect(() => {
operate tick() {
savedCallback.present();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}

I’ll cease right here for now, however I consider these examples ought to offer you a good suggestion of what’s doable with customized hooks.

You’ll be able to create a customized hook for just about something you want. The sky’s the restrict! So go forward, begin creating and utilizing customized hooks, and make your code cleaner and extra reusable than ever earlier than.

[ad_2]

Leave a Reply

Your email address will not be published. Required fields are marked *