React Native TextInput Value persist when Tab is changed

I have encountered a weird issue in the newest react native where the value in the text input in a component remains when a tab is switched.

I can’t figure what is going on and I thought it should re-render when tab is changed but it doesn’t.

Here’s my code
app.js

export default function App() {
  const [tab, setTab] = useState("TAB1")
  return (
    <View style={styles.container}>
      <View style={{ flexDirection: 'row' }}>
        <TouchableOpacity
          style={{ borderRadius: 5, borderWidth: 1, marginRight: 5, padding: 20 }}
          onPress={() => setTab("TAB1")}
        >
          <Text>Tab 1</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={{ borderRadius: 5, borderWidth: 1, padding: 20}}
          onPress={() => setTab("TAB2")}
        >
          <Text>Tab 2</Text>
        </TouchableOpacity>
      </View>
      <View style={{ marginTop: 20}}>
        {
          tab === "TAB1" ? (
            <View>
              <InputComponent tab={tab} />
            </View>
          ) : (
              <View>
                <InputComponent tab={tab} />
              </View>
            )
        }
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    marginTop: 100,
    padding: 10
  },
});

inputcomponent.js

export function InputComponent({ tab }) {
    const [value, setValue] = useState("");

    return (
        <View>
            <Text>{tab}</Text>
            <TextInput placeholder="INPUT HERE"  value={value} onChangeText={setValue}/>
        </View>
    )
}

It seems like the input component re-renders but the text input within it doesn’t change.

Demo Issue

1 thought on “React Native TextInput Value persist when Tab is changed”

  1. This is such a good question. This is because we are importing it once and passing it to two different components. It changes the tab but uses the same textinput state because they are using the same key.

    To fix this pass in the key prop so React knows that tab changed:

    {
          tab === "TAB1" ? (
            <View>
              <InputComponent key={1} tab={tab} />
            </View>
          ) : (
              <View>
                <InputComponent key={2} tab={tab} />
              </View>
            )
        }
    

    Snack: https://snack.expo.io/mVVLb9uId

    Read about keys: https://reactjs.org/docs/lists-and-keys.html#keys

    Reply

Leave a Comment