Props and State

Loading concept...

🎁 Props & State: The Gift-Giving Game of React Native

Imagine you’re at a birthday party. Some kids bring gifts to share (that’s Props), and some kids have their own secret toy boxes they can open and change anytime (that’s State). Let’s learn how React Native apps share information and remember things!


🎯 The Big Picture

In React Native, components are like LEGO blocks. They need two things:

  1. Props = Gifts from parents (read-only, can’t change them)
  2. State = Your own toy box (you control it, you change it)
graph TD A[Parent Component] -->|Props 🎁| B[Child Component] B -->|Has its own| C[State 📦] C -->|Changes trigger| D[Re-render 🔄]

📦 Props Fundamentals

What Are Props?

Props are like birthday gifts. When your parent gives you a gift, you can use it but you can’t change what’s inside. That’s exactly how props work!

Think of it this way:

  • Your mom gives you a red balloon 🎈
  • You can hold it, play with it, show it to friends
  • But you can’t magically make it blue

How Props Flow

Props always flow DOWN - from parent to child. Never up!

// Parent gives a gift
function ParentComponent() {
  return (
    <ChildComponent
      name="Emma"
      age={8}
    />
  );
}

// Child receives the gift
function ChildComponent(props) {
  return (
    <Text>
      Hi, I'm {props.name}!
      I'm {props.age} years old.
    </Text>
  );
}

Output: “Hi, I’m Emma! I’m 8 years old.”

Destructuring Props (The Cool Way)

Instead of saying props.name every time, unwrap your gifts at the door!

function ChildComponent({ name, age }) {
  return (
    <Text>
      Hi, I'm {name}!
      I'm {age} years old.
    </Text>
  );
}

Same result, cleaner code! 🧹


🎯 Default Props

What If No Gift Arrives?

Sometimes parents forget to send a gift. No problem! We set up backup gifts - that’s Default Props.

function Greeting({ name = "Friend" }) {
  return <Text>Hello, {name}!</Text>;
}

// Using it:
<Greeting />
// Output: "Hello, Friend!"

<Greeting name="Alex" />
// Output: "Hello, Alex!"

Multiple Default Props

function ProfileCard({
  name = "Anonymous",
  age = 0,
  emoji = "😊"
}) {
  return (
    <View>
      <Text>{emoji} {name}</Text>
      <Text>Age: {age}</Text>
    </View>
  );
}

Why this matters: Your app won’t crash if something is missing!


👶 Children Props

The Special Magic Backpack

There’s a secret prop called children. It’s like a magic backpack - whatever you put BETWEEN the opening and closing tags goes inside!

function MagicBox({ children }) {
  return (
    <View style={styles.box}>
      {children}
    </View>
  );
}

// Using it:
<MagicBox>
  <Text>I'm inside the box!</Text>
  <Text>Me too! 🎉</Text>
</MagicBox>

Real Example: A Card Wrapper

function Card({ children, title }) {
  return (
    <View style={styles.card}>
      <Text style={styles.title}>
        {title}
      </Text>
      {children}
    </View>
  );
}

// Using it:
<Card title="My Profile">
  <Image source={avatar} />
  <Text>Welcome back!</Text>
</Card>

Children props let you create reusable wrappers. Like a picture frame that can hold ANY picture!


🪝 useState Hook

Your Personal Toy Box

Now for the exciting part! State is YOUR toy box. You can:

  • Look inside (read it)
  • Add toys (update it)
  • Remove toys (update it)

Unlike props, YOU control your state!

The Magic Spell: useState

import { useState } from 'react';

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

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

Breaking it down:

  • count = current value (starts at 0)
  • setCount = function to change it
  • useState(0) = initial value is 0
graph TD A[useState 0] -->|Creates| B[count = 0] A -->|Creates| C[setCount function] D[User taps button] -->|Calls| C C -->|Updates| E[count = 1] E -->|Triggers| F[Screen updates!]

Different Types of State

// Number state
const [age, setAge] = useState(10);

// String state
const [name, setName] = useState("Sam");

// Boolean state
const [isHappy, setIsHappy] = useState(true);

// Array state
const [toys, setToys] = useState([]);

// Object state
const [user, setUser] = useState({
  name: "Sam",
  age: 10
});

🔄 State Update Patterns

Pattern 1: Direct Update

When new value doesn’t depend on old value:

const [color, setColor] = useState("red");

// Direct update
setColor("blue");

Pattern 2: Functional Update

When new value DEPENDS on old value, use a function:

const [score, setScore] = useState(0);

// ✅ CORRECT - Uses previous value
setScore(prev => prev + 10);

// ❌ RISKY - Might miss updates
setScore(score + 10);

Why functional updates? React batches updates. If you click really fast, direct updates might “lose” some clicks. Functional updates NEVER lose data!

Pattern 3: Toggle Boolean

const [isOn, setIsOn] = useState(false);

// Toggle pattern
const handleToggle = () => {
  setIsOn(prev => !prev);
};

Real example: Light switch, checkbox, show/hide menu

Pattern 4: Increment/Decrement

const [quantity, setQuantity] = useState(1);

const increment = () => {
  setQuantity(prev => prev + 1);
};

const decrement = () => {
  setQuantity(prev =>
    prev > 0 ? prev - 1 : 0
  );
};

📚 Object and Array State

Object State: The Treasure Chest

Objects hold multiple related values together. But updating them is tricky!

The Golden Rule: Never change state directly. Always create a NEW object!

const [person, setPerson] = useState({
  name: "Mia",
  age: 7,
  hobby: "drawing"
});

// ❌ WRONG - Mutating directly
person.age = 8;

// ✅ CORRECT - Create new object
setPerson({
  ...person,      // Copy old stuff
  age: 8          // Update one thing
});

The ...person is called spread operator. It copies everything from the old object!

Updating Nested Objects

const [user, setUser] = useState({
  name: "Leo",
  address: {
    city: "Tokyo",
    zip: "12345"
  }
});

// Update nested property
setUser({
  ...user,
  address: {
    ...user.address,
    city: "Osaka"
  }
});

Array State: The Toy Lineup

Arrays are lists of things. Same rule: never change directly, always create new!

const [fruits, setFruits] = useState([
  "apple", "banana"
]);

Add item to end:

setFruits([...fruits, "orange"]);
// Result: ["apple", "banana", "orange"]

Add item to start:

setFruits(["mango", ...fruits]);
// Result: ["mango", "apple", "banana"]

Remove item:

setFruits(
  fruits.filter(f => f !== "banana")
);
// Result: ["apple"]

Update item:

setFruits(
  fruits.map(f =>
    f === "apple" ? "green apple" : f
  )
);
// Result: ["green apple", "banana"]

Array of Objects (The Real World)

const [todos, setTodos] = useState([
  { id: 1, text: "Learn props", done: false },
  { id: 2, text: "Learn state", done: false }
]);

// Mark one as done
const completeTodo = (id) => {
  setTodos(
    todos.map(todo =>
      todo.id === id
        ? { ...todo, done: true }
        : todo
    )
  );
};

// Add new todo
const addTodo = (text) => {
  setTodos([
    ...todos,
    { id: Date.now(), text, done: false }
  ]);
};

// Delete todo
const deleteTodo = (id) => {
  setTodos(
    todos.filter(todo => todo.id !== id)
  );
};
graph TD A[Array of Objects] -->|map| B[Update items] A -->|filter| C[Remove items] A -->|spread + new| D[Add items] B --> E[New Array Created] C --> E D --> E E --> F[State Updated!]

🎨 Putting It All Together

Here’s a mini app using EVERYTHING we learned:

function TodoApp() {
  // State for todos (array of objects)
  const [todos, setTodos] = useState([]);
  // State for input
  const [input, setInput] = useState("");

  const addTodo = () => {
    if (input.trim()) {
      setTodos(prev => [
        ...prev,
        { id: Date.now(), text: input }
      ]);
      setInput("");
    }
  };

  return (
    <View>
      <TextInput
        value={input}
        onChangeText={setInput}
        placeholder="Add todo..."
      />
      <Button title="Add" onPress={addTodo} />

      {todos.map(todo => (
        <TodoItem
          key={todo.id}
          text={todo.text}
        />
      ))}
    </View>
  );
}

// Child receives props
function TodoItem({ text }) {
  return <Text>• {text}</Text>;
}

🏆 Quick Summary

Concept What It Is Remember
Props Gifts from parent Read-only!
Default Props Backup gifts Prevents crashes
Children Props Magic backpack Content between tags
useState Your toy box You control it
Functional Updates Safe updates Use prev =>
Object State Treasure chest Always spread ...
Array State Toy lineup map, filter, spread

🌟 You Did It!

You now understand the TWO most important concepts in React Native:

  • Props = How components talk to each other
  • State = How components remember and change

Like a birthday party, parents share gifts (props), and kids manage their own toy boxes (state). Together, they create amazing apps!

Next step: Practice! Build a counter, a todo list, or a simple game. The more you practice, the more natural it becomes.

Happy coding! 🚀

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.