State Management

Incrementing Number

Suppose we want to build an an app with the following requirements:

  1. A Text component displaying the counter value, with an initial value of 0.

  2. A Button to increment the counter.

  3. Another Button to decrement the counter.

Wrong Example

Without knowledge on React state management, our knowledge of javascript would tell us to do something like this:

function Component() {
  let counter = 0;
  
  // DON'T DO THIS - mutating counter doesn't tell React to re-render
  return <Button onPress={() => counter += 1} />;
}

React Native doesn’t know when to re-render a component if we simply use let counter = 0 and update it. This breaks the rules for props since it involves mutating the value directly.

Correct Example

Instead, React provides the useState hook to manage state changes and trigger re-renders appropriately.

function Component() {
  const [counter, setCounter] = useState(0);
  
  // This is correct - the counter value is updated in the next render
  return <Button onPress={() => setCounter(counter + 1)} />;
}

Managing Text

State is used in various components, such as TextInput, where the text changes every time the user types something. We use useState to track and update the text.

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

const TextInputComponent = () => {
  const [text, setText] = useState('');

  return (
    <View>
      <TextInput 
        style={styles.input} 
        value={text} 
        onChangeText={setText} 
        placeholder="Type here"
      />
    </View>
  );
};

Conditional Rendering

Conditional rendering allows components to render dynamically based on the state. Here’s an example with a modal:

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

const ModalComponent = () => (
  <View>
    <Text>This is a modal!</Text>
  </View>
);

const App = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const toggleModal = () => {
    setIsModalOpen(!isModalOpen);
  };

  return (
    <View >
      <Button title="Toggle Modal" onPress={toggleModal} />
      {isModalOpen && (
        <Modal
          transparent={true}
          visible={isModalOpen}
          onRequestClose={toggleModal}
        >
          <View>
            <ModalComponent />
            <Button title="Close Modal" onPress={toggleModal} />
          </View>
        </Modal>
      )}
    </View>
  );
};

In this example, the toggleModal function toggles the isModalOpen state, which conditionally renders the ModalComponent.

Last updated