Skip to content
Advertisement

How to avoid re rendering text input?

I have a TextInput and I don’t want it to re render every time I change the value inside it

const [WrittenVal,setWrittenVal] = useState(()=>'');
...
    <TextInput
        value={String(WrittenVal)}
        onChangeText={text => setWrittenVal(text)}
    />

but I want to be able to change the value inside the input at the push of a button that’s why I haven’t just used defaultValue

any solutions??

Advertisement

Answer

You can use useRef to save text from text input without render , and useState to show text in input on button press:

Live example : https://snack.expo.dev/TW-fMx1-2

import React from "react";
import { SafeAreaView, StyleSheet, TextInput,TouchableOpacity,Text } from "react-native";

const UselessTextInput = () => {
  const [text, onChangeText] = React.useState("");

  const textRef = React.useRef('')

  const textToRef = (text) =>{
    textRef.current = textRef.current + text
  }

  const showTextInInput = () =>{
    onChangeText( textRef.current )
  }

  console.log("render")
  return (
    <SafeAreaView>
      <TextInput
        style={styles.input}
        onChangeText={textToRef}
        value={text}
      />
      <TouchableOpacity onPress={showTextInInput}>
          <Text>SHOW TEXT IN INPUT</Text>
      </TouchableOpacity>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  input: {
    height: 40,
    margin: 12,
    borderWidth: 1,
    marginTop:50,
    padding: 10,
  },
});

export default UselessTextInput;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement