Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement