React useRef

Created By: chatGPT

useRef is a powerful hook in React that allows you to create a mutable reference to a DOM element or a value that persists across render cycles. Unlike state, changing a ref does not trigger a re-render of the component. This can be useful for accessing DOM nodes directly or storing any mutable value without causing an update of the component tree.
import React, { useRef } from 'react';

const MyComponent = () => {
    // Create a ref using useRef
    const inputRef = useRef(null);

    const focusInput = () => {
        // Access the current value of the ref to focus the input element
        if (inputRef.current) {
            inputRef.current.focus();
        }
    };

    return (
        <div>
            <input ref={inputRef} type="text" placeholder="Click the button to focus here" />
            <button onClick={focusInput}>Focus Input</button>
        </div>
    );
};

export default MyComponent;
In this example, we create a ref using useRef and assign it to an input element. When the button is clicked, the focusInput function is called, which uses the ref to focus on the input field. Here’s how it works:
const inputRef = useRef(null);  // Initialize ref

// Use inputRef.current to access the DOM element
if (inputRef.current) {
    inputRef.current.focus(); // Focus the input element
}
useRef can also be utilized to hold any mutable value. For instance, if you want to keep track of a counter without re-rendering the component, you can do so like this:
const MyCounterComponent = () => {
    const countRef = useRef(0);

    const incrementCount = () => {
        countRef.current += 1;
        console.log(countRef.current);
    };

    return (
        <div>
            <button onClick={incrementCount}>Increment Count</button>
        </div>
    );
};

export default MyCounterComponent;
In this case, countRef.current retains its value even after the component re-renders when the button is clicked. This allows you to manage values or states that do not necessarily require the component to update the UI directly.
const countRef = useRef(0);

// Increment the current count value
countRef.current += 1;
console.log(countRef.current); // Logs the current count
Introduction And SetupComponentsPropsStateLifecycle MethodsHooksContext APIJsx SyntaxVirtual DomEvent HandlingFormsRoutingPerformance OptimizationError BoundariesHigher Order ComponentsRender PropsPortalsFragmentsRefsControlled ComponentsUncontrolled ComponentsMemoizationSuspenseLazy LoadingProp TypesDefault PropsConditional RenderingList And KeysAccessibility (a11y)State ManagementTestingCustom HooksUseEffectUseStateUseContextUseReducerUseMemoUseCallbackUseRefUseLayoutEffectUseImperativeHandleUseDebugValueAutomatic BatchingSuspense For Data FetchingStrict ModeForward RefsCreateContextLazyUseTransitionUseDeferredValueUseId