Open In App

Additional Built-in Hooks in React

Hooks are functions that allow you to "hook" into the state of a component and provide additional features to ensure the lifespan of functional components. These are available in React versions 16.8.0 and higher. however, we previously used to describe them using classes.

We will discuss the various Additional Built-in Hooks:

The useReducer hook

useReducer Hook provides an alternative to useState for managing complex state logic. It's often used when state transitions depend on the previous state or when the next state depends on the previous state.

Syntax:

const [state, dispatch] = useReducer(reducer, initialState);

Example: Below is an example of useReducer hook.

import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return { count: state.count + 1 };
        case 'decrement':
            return { count: state.count - 1 };
        default:
            throw new Error();
    }
}

function Gfgarticle() {
    const [state, dispatch] = useReducer(reducer, initialState);

    return (
        <>
            Count: {state.count}
            <br></br>
            <button onClick={() => dispatch({ type: 'increment' })}>
                Increment
            </button> &nbsp;
            <button onClick={() => dispatch({ type: 'decrement' })}>
                Decrement
            </button>
        </>
    )
};
export default Gfgarticle;

Output:

UseReducer-ezgifcom-video-to-gif-converter

The useRef hook

useRef hook helps to return a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

Syntax:

const refContainer = useRef(initialValue);

Example: Below is an example of useRef hook.

import React, {
    useState,
    useEffect,
    useRef
} from 'react';

function Gfgarticle() {
    const [inputValue, setInputValue] = useState("");
    const count = useRef(0);

    useEffect(() => {
        count.current = count.current + 1;
    });

    return (
        <>
            <input type="text" value={inputValue}
                onChange={(e) => setInputValue(e.target.value)} />
            <h1>
                The page has been rendered {count.current} times
            </h1>
        </>
    );

}
export default Gfgarticle;

Output:

useRef-ezgifcom-video-to-gif-converterThe useCallback Hook

useCallback hook helps to return a memoized callback that only changes if one of the dependencies has changed. This can help optimize performance by preventing unnecessary re-renders of child components.

Syntax:

const memoizedCallback = useCallback(
() => {
// Function logic
},
[dependencies]
);

Example: Below is an example of useCallback hook.

import React, {
    useState,
    useCallback
} from 'react';

function Gfgarticle() {
    const [count, setCount] = useState(0);
    const increment = useCallback(() => {
        setCount((prevCount) => prevCount + 1);
    }, []);

    return (
        <>
            <p>Count: {count}</p>
            <button onClick={increment}>
                Incement
            </button>
        </>
    )
}
export default Gfgarticle;

Output:

usecallback-ezgifcom-video-to-gif-converter

The useMemo Hook

useMemo Hook returns a memoized value. It will only recompute the memoized value when one of the dependencies has changed. It is basically used to do expensive calculation only when the dependencies change.

Syntax:

const memoizedValue = useMemo(() => {
// Computation
return expensive Computation value;
}, [dependencies]);

Example: Below is an example of useMemo hook.

import React, {
    useState,
    useMemo
} from 'react';

function Gfgarticle({ count }) {
    const [count, setCount] = useState(0);
    const [number, setNumber] = useState(0);
    const expensiveCalculation = (num) => {
        for (let i = 0; i < 100000000; i++) {
            num += i;
        }
        return num;
    };
    const increment = () => {
        setCount(count + 1);
        if (count % 10 === 0) {
            setNumber(count + 1);
        }
    }

    const calculation = useMemo(
        () => expensiveCalculation(number), [number]);
    return (
        <>
            <h1>This is a Memo Hook</h1>
            <div>Count: {count}</div>
            <button onClick={increment}>
                Increase
            </button>
            <h2>Expensive Calculation</h2>
            {calculation}
        </>
    )
}
export default Gfgarticle;

Output:

UseMemo-ezgifcom-video-to-gif-converter

The useLayoutEffect Hook

useLayoutEffect Hook is similar to useEffect. But it fires synchronously after all DOM mutations. This can be useful for measuring DOM nodes or performing layout calculations. It is best to find the dimensions.

Syntax:

useLayoutEffect(() => {
// Effect function
// Perform synchronous operations requiring DOM measurements or layout calculations
// Return a cleanup function (optional)
return () => {
// Cleanup logic
};
}, [dependencies]);

Example: Below is an example of useLayoutEffect hook.

import React, {
    useLayoutEffect,
    useState,
    useRef
} from 'react';

function Gfgarticle() {
    const [width, setWidth] = useState(0);
    const ref = useRef();

    useLayoutEffect(() => {
        setWidth(ref.current.clientWidth);
    }, []);

    return (
        <>
            <h1>This is useLayoutEffect Hook</h1>
            <p ref={ref}>Width: {width}px</p>
        </>
    )
};
export default Gfgarticle;

Output:

Uselayouteffect-ezgifcom-video-to-gif-converter

The useImperativeHandle Hook

It is a React hook that allows you to customize the instance value that is exposed when using 'ref' with 'React.forwardRef'. It's particularly useful when you're working with third-party libraries or integrating with imperative APIs and need more control over the exposed methods or properties of a component.

Syntax:

useImperativeHandle(ref, () => {
// Return an object representing the public API of the component
return {
exposedFunction1,
exposedFunction2,
};
}, [dependencies]);

Example: Below is an example of useImperativeHandle hook.

import React, {
    useRef,
    useImperativeHandle,
    forwardRef
} from 'react';

// Child component that forwards a ref
const ChildComponent = forwardRef((props, ref) => {
    const inputRef = useRef(null);

    // Expose custom imperative methods
    useImperativeHandle(ref, () => ({
        focus: () => {
            inputRef.current.focus();
        },
        reset: () => {
            inputRef.current.value = '';
        }
    }));

    return <input ref={inputRef} />;
});

// Parent component using the child component
function Gfgarticle() {
    const childRef = useRef(null);

    const handleFocusClick = () => {
        childRef.current.focus();
    };

    const handleResetClick = () => {
        childRef.current.reset();
    };

    return (
        <div>
            <h1>This is useImperativeHandle Hook</h1>
            <ChildComponent ref={childRef} /><br></br><br></br>
            <button onClick={handleFocusClick}>
                Focus Input
            </button>
            &nbsp;
            <button onClick={handleResetClick}>
                Reset Input
            </button>
        </div>
    );
}

export default Gfgarticle;

Output:

UseImphandle-ezgifcom-video-to-gif-converter

The useDebugValue Hook

useDebugValue Hook in React is used to display additional debug information for custom hooks in React DevTools. It's primarily used for development purposes to provide more insights into the state or behavior of custom hooks.

Syntax:

useDebugValue(value, formatter);

Example: Below is an example of useDebugValue hook.

import React, {
    useState,
    useEffect,
    useDebugValue
} from 'react';

function Gfgarticle() {
    const [count, setCount] = useState(0);

    // Displaying count value in React DevTools
    useDebugValue(count > 0 ?
        'Positive' : 'Non-positive');

    useEffect(() => {
        const timer = setInterval(() => {
            setCount((prevCount) => prevCount + 1);
        }, 1000);

        return () => clearInterval(timer);
    }, []);

    return <div>Count: {count}</div>;
};

export default Gfgarticle;

Output:

UseDebugvalue-ezgifcom-video-to-gif-converter

Conclusion

In conclusion, React's built-in hooks revolutionized the way developers write components by providing a powerful and intuitive way to manage state, effects, context, and more within functional components. Introduced in React version 16.8.0, hooks enable developers to leverage advanced React features without relying on class components, leading to cleaner, more concise code and improved code reuse.

Article Tags :