useState- Hook in React Native

useState is a React Hook that lets you add state management to your functional components in both React and React Native. It allows you to manage state variables in a simple and concise manner.
const [state, setState] = useState(initialValue);

  • state: The current state value.
  • setState: A function to update the state.
  • initialValue: The initial value of the state.

Example: Counter App

Here’s how you can use useState in a simple React Native app to create a counter:


import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

const CounterApp = () => {
  const [count, setCount] = useState(0);

  function first(){
    setCount(count+1)
  }

  function second(){
    setCount(count-1)
  }

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Count: {count}</Text>
      <Button title="Increase" onPress={first} />
      <Button title="Decrease" onPress={second} />
      {/* <Button title="Reset" onPress={() => setCount(0)} /> */}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 24,
    marginBottom: 20,
  },
});

export default CounterApp;

Key Points

  1. State Initialization: You pass the initial state value (0 in this example) to useState.
  2. State Update: Use the setState function (e.g., setCount) to update the state. React Native will re-render the component when the state changes.
  3. Immutability: Avoid directly modifying the state variable; always use the setter function.