useRef and useEffect initial access and then later usage of useRef

437 views Asked by At

How can I wait for ref to be ready but also only work inside my use effect with condition?

Here is what I want to do:

I want to select all rows in my DataGrid component using ref when popup is visible.

This code won't work, because I don't have ref current instance at that time.

useEffect(() => {
  if (isVisible) {
    dataGridRef.current.instance.selectAll()
  }
}, [isVisible])

So I searched and found useCallback to update when ref is connected.

const dataGridRef = useCallback(node => {
    if (node !== null) {
      node.instance.selectAll()
    }
  }, [])

<DataGrid ref={dataGridRef} ..

But this time, I cannot use ref instance when I have to reset(unselect data grid using ref)

2

There are 2 answers

1
Jacob K On BEST ANSWER

Your callback ref will capture when changes are made to the node, and in that same function execution, you can update a ref object to be referenced outside the callback at your whims.

// define a ref object and a ref function
const dataGridRef = useRef(null);
const dataGridFuncRef = useCallback(node => {

  // manually update the ref object each time the dom element changes
  dataGridRef.current = node.instance;
  node.instance?.selectAll();

}, []);

const deselectOnClick = (event) => {
  // now we can use the ref instance outside the callback
  dataGridRef.current?.instance?.deselectAll();
}

// ... inside the render function ...

<DataGrid ref={dataGridFuncRef} />

Here is an example CodeSandbox of the above concepts.

0
kanuos On

You can try doing something like

    useEffect(() => {
  if (isVisible && dataGridRef?.current) {
    dataGridRef.current.instance.selectAll()
  }
}, [isVisible])

Additionally you could chain ? operator to check for null