Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rerender when refs change

Tags:

Code:

import DrawControl from "react-mapbox-gl-draw";  export default function MapboxGLMap() {     let drawControl = null     return(       <DrawControl ref={DrawControl => {drawControl = DrawControl}}/>     ) } 

I want to load data when the drawControl not null. I check the document that may use callback ref.

So, how do I listen the drawControl changes and load data?

like image 753
Yang Yun Avatar asked Jan 05 '20 13:01

Yang Yun


People also ask

Does Ref change cause Rerender?

And since changing ref doesn't cause the component to re-render, the button stays active. To demonstrate this point further, let's add a parent component. By default when you render a React component it recursively re-renders all its children.

Does useRef trigger Rerender?

[2:52] In summary, useRef can be used to store data values just like useState, but the difference is that when that value changes, it doesn't cause a re-render.

How do you trigger a Rerender?

Forcing an update on a React class component In any user or system event, you can call the method this. forceUpdate() , which will cause render() to be called on the component, skipping shouldComponentUpdate() , and thus, forcing React to re-evaluate the Virtual DOM and DOM state.


1 Answers

If you want to trigger a re-render after the ref changes, you must use useState instead of useRef. Only that way can you ensure that the component will re-render. E.g.:

function Component() {   const [ref, setRef] = useState();    return <div ref={newRef => setRef(newRef)} /> } 

As described under useRef documentation:

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

It may sometimes be better to store whatever value you are getting from the DOM node, as suggested here, instead of storing the node itself.

like image 163
ArneHugo Avatar answered Sep 21 '22 18:09

ArneHugo