David Peer
David Peer

Reputation: 170

Why use refs in react? What is the use cases for it?

This question exists but it didn't give a lot of data or real world explanation: What are Refs in React or React-Native and what is the importance of using them

Let's say i want to integrate to 3rd party library how ref is going to help me?

Upvotes: 3

Views: 3363

Answers (4)

Vijay122
Vijay122

Reputation: 964

Whenever you want to use the properties of child from a parent, we refer it with a ref id, this is to ensure we are executing on the right child component. The properties can be either states, props of functions defined in the child component.

Upvotes: 2

glinda93
glinda93

Reputation: 8459

Some 3rd party libraries expose methods to interact with their components.

For example, in react-native-elements npm, they have shake method for Input component. You can use this method to shake Input element when user input is invalid.

Common use case is as follows:

import React from 'react';
import { Input, Button } from 'react-native-elements';
const [value, setValue] = useState('');
const input = React.createRef();

return (
  <View>
    <Input
      ref={input}
      onTextChange={(text) => setValue(text)}
    />
    <Button 
      title={'Submit'}
      onPress={() => {
        if (!isValid(value)) {
          input.current.shake();
        }
      }}
    />
  </View>
);

This is react native example, but the similar goes to react projects. I hope you get the picture. Animations like shake cannot be easily handled with state, so it's better to use useRef to call component methods directly.

Upvotes: 4

Elias Schablowski
Elias Schablowski

Reputation: 2812

Let's say i want to integrate to 3rd party library how ref is going to help me?

Refs let you access the DOM directly, thus you can use vanilla js libraries using refs, for example you could use jQuery like $(ref). This simplifies and makes getting DOM nodes less error prone than using other techniques such as adding classes/ids to every element and then using selectors since these methods do not stop you from accessing nodes not created by you.

Long story short, Refs let you treat react elements as though they were vanilla js

Upvotes: 3

Mustakim
Mustakim

Reputation: 429

React useRef help us to accessing dom elements before its rendering. You can go through it

https://reactjs.org/docs/refs-and-the-dom.html

Upvotes: 2

Related Questions