Getting ref null inside useCallback hook

I’m trying to set the value of input using ref but I’m getting ref null inside useCallback Hook.

let inputRef = useRef();
const search = useCallback(
        (data) => {
            console.log(inputRef);
        },
        [inputRef],
    );

return <input type="text" ref={inputRef} />

and It’s showing null in the browser console when I call this function.

this is just an example showing, what I’m trying to achieve.

7 thoughts on “Getting ref null inside useCallback hook”

  1. Probably you need to pass null to useRef() first. Then you can access with inputRef.current.

    Try as the following:

    let inputRef = useRef(null);
    
    const search = useCallback((data) => {
       console.log(inputRef.current);
    }, [inputRef]);
    
    return <input type="text" ref={inputRef} />
    

    From the documentation of useRef():

    useRef returns 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.

    I hope this helps!

    Reply
  2. The problem isn’t that he’s not passing in a null value, a ref is initialized to null by default.

    The problem is that useCallback memoizes and caches the result of this callback function before the first render, before the component to which this ref is assigned has been mounted. It then waits for inputRef to change but inputRef is just a reference to an object and even if the component the ref points to changes, the value of inputRef does not as it is only being compared by reference equality

    So, since the function has no reason to update as the value of inputRef is not going to change — it evaluates to the cached result of the search callback as it was before the DOM mounted and outputs null to console.

    Reply

Leave a Comment