Storing non-state variables in functional components

后端 未结 4 1122
梦谈多话
梦谈多话 2020-12-25 10:45

Below are two React Components that do almost the same thing. One is a function; the other is a class. Each Component has an Animated.Value with an asy

4条回答
  •  Happy的楠姐
    2020-12-25 11:16

    Just to support Tholle answer here is the official documentation

    Reference

    However, useRef() is useful for more than the ref attribute. It’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.

    This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.

    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.

提交回复
热议问题