0
0
React Nativemobile~5 mins

Why state and props drive component behavior in React Native

Choose your learning style9 modes available
Introduction

State and props control what a component shows and how it acts. They help the app update and respond to user actions.

When you want a button to change its label after being pressed.
When you need to show different text based on user input.
When passing information from a parent screen to a child screen.
When you want to update a list after adding or removing items.
When you want to keep track of user choices inside a screen.
Syntax
React Native
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';

function MyComponent(props) {
  const [stateValue, setStateValue] = useState(initialValue);
  return (
    <View>
      <Text>{props.someProp}</Text>
      <Button onPress={() => setStateValue(newValue)} title="Press me" />
    </View>
  );
}
props are values passed from a parent component to a child component.
state is data managed inside the component that can change over time.
Examples
This component uses props to show a name passed from its parent.
React Native
import React from 'react';
import { Text } from 'react-native';

function Greeting(props) {
  return <Text>Hello, {props.name}!</Text>;
}
This component uses state to keep track of a number that changes when the button is pressed.
React Native
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <View>
      <Text>Count: {count}</Text>
      <Button onPress={() => setCount(count + 1)} title="Add" />
    </View>
  );
}
Sample App

This app shows text that changes color when you press the button. The color is stored in state. It also shows a message passed from the parent using props.

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

export default function ColorChanger(props) {
  const [color, setColor] = useState('blue');

  return (
    <View style={{ padding: 20, alignItems: 'center' }}>
      <Text style={{ color: color, fontSize: 24 }}>This text changes color!</Text>
      <Button
        title="Change to red"
        onPress={() => setColor('red')}
        accessibilityLabel="Change text color to red"
      />
      <Text style={{ marginTop: 10 }}>Parent says: {props.message}</Text>
    </View>
  );
}
OutputSuccess
Important Notes

Changing state causes the component to update and show new data.

props are read-only inside the component; you cannot change them there.

Use state for data that changes inside the component, and props for data passed from outside.

Summary

State holds data that can change inside a component.

Props pass data from parent to child components.

Together, they control what the component shows and how it behaves.