Home
Basics
Introduction Setting up environment First Component JSX Component lifecycle Class Based Components Function Based Components Props State Hooks useState hook useEffect hook Events Server requests CSS in React Router third party JavaScriptAdvanced
useContext hook useRef hook useReducer hook Memo useCallback hook Custom Hooks React and ReduxMiscellaneous
React Third Party Components Html templates in React React Interview QnACustom hooks in react
Custom hooks can be created when you want to avoid duplicate code and functionality in the application. For example - Let us say there are 2 components which need to take action when user resized the window. So we can write a code to add even listener on resize. This code can be put in a custom hook and can be reused in both components.
import { useState, useEffect } from "react";
export const useWindowResize = () => {
//state to store width and height of window
const [width, setWidth] = useState(window.innerWidth);
const [height, setHeight] = useState(window.innerHeight);
const functionToCallOnResize = () => {
setWidth(window.innerWidth);
setHeight(window.innerHeight);
};
useEffect(() => {
//add resize event listener on component mount
window.addEventListener("resize", functionToCallOnResize);
//remove resize event listener on component mount
return () => {
window.removeEventListener("resize", functionToCallOnResize);
};
}, []);
//return width and height of window after resize event
return {
width,
height,
};
};
// to use above hook, you can use below syntax
let windowDimensions = useWindowResize()
if (windowDimensions.height <= '400'){
console.log("Window height less than 400")
}
Web development and Automation testing
solutions delivered!!