How to use useRef Hook in React Native Functional Component

Last Updated on September 5, 2020.

Hooks are integral part of a functional component. The useRef hook is used to invoke methods on react native components. In this blog post, let’s check how to use useRef in react native.

We have a TextInput component and a Pressable component. When we press the Pressable component, the text inside TextInput should be cleared by invoking clear method. If you are new to functional components in react native, then please go through this blog post before proceeding.

We use UseRef hook to invoke clear method as given in the following react native example.

import React, {useState, useRef} from 'react';
import {TextInput, View, Pressable, Text} from 'react-native';

const App = () => {
  const inputRef = useRef();
  const [input, setInput] = useState('');
  const pressed = () => {
    inputRef.current.clear();
  };
  return (
    <View style={{flex: 1}}>
      <TextInput
        ref={inputRef}
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => setInput(text)}
        value={input}
      />
      <Pressable onPress={pressed}>
        <Text>Clear it!</Text>
      </Pressable>
    </View>
  );
};

export default App;

The output of the above example is given below.

I hope this tutorial has helped you!

2 thoughts on “How to use useRef Hook in React Native Functional Component”

  1. Pingback: How to Add Scroll to Top Functionality to FlatList in React Native - REACT NATIVE FOR YOU

Leave a Reply

%d bloggers like this: