Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 360
David Peer Avatar asked Dec 11 '25 07:12

David Peer


1 Answers

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.

like image 176
glinda93 Avatar answered Dec 12 '25 21:12

glinda93