Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Managing State with useState | State, Props, and Data Flow
React Native Fundamentals

Managing State with useState

Swipe um das Menü anzuzeigen

React Native lets you build interactive mobile apps using components. Sometimes, you need your components to remember information or respond to user actions—this is where state comes in. In functional components, you manage state with the useState hook. The useState hook allows you to add local state to your component so it can store and update values over time.

The syntax for useState is simple. You call useState inside your component and pass in the initial value for your state. It returns an array with two elements: the current state value, and a function to update that value. You typically use array destructuring to give these two elements meaningful names. Here is the basic syntax:

const [value, setValue] = useState(initialValue);
  • value: the current state value;
  • setValue: a function that lets you update the state;
  • initialValue: the value you want the state to start with.

You can call setValue whenever you want to update the state. When the state changes, the component re-renders to reflect the new value.

To see how useState works in practice, consider a simple counter component. This component will display a number and let the user increase or decrease it by pressing buttons. Here is how you can use useState to track and update the counter value:

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

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <View>
      <Text>Count: {count}</Text>
      <Button title="Increase" onPress={() => setCount(count + 1)} />
      <Button title="Decrease" onPress={() => setCount(count - 1)} />
    </View>
  );
}

In this example, the Counter component uses useState(0) to create a count variable, starting at 0. The setCount function updates the value of count. When you press the "Increase" button, setCount(count + 1) is called, which adds 1 to the current count. When you press "Decrease," it subtracts 1. Each time the state updates, React Native re-renders the component so the new value appears on the screen.

This pattern lets you manage any kind of local state in your components, such as form input, toggles, or user interactions. The useState hook is a fundamental tool for building interactive UIs in React Native.

question mark

Which hook is used to add state to a functional component in React Native?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 4. Kapitel 2

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 4. Kapitel 2
some-alt