Web Development · Module 9 · Lesson 21 min read

Props & State

Props: data passed into a component

React
function Greeting({ name, emoji = "👋" }) {
  return <p>{emoji} Hello, {name}!</p>;
}
<Greeting name="Ana" />
  • Props are read-only inside the component.
  • Pass functions as props so children can tell parents something: onDelete={() => remove(id)}.
  • children is the content between the tags: <Card>…</Card>.

State: data that changes over time

React
import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}
  • Calling the setter re-renders the component with the new value.
  • Never change state directly (count++); always use the setter.
  • When the new value depends on the old one, use the functional form: setCount((c) => c + 1).
  • For objects and arrays, create new copies: setTodos([...todos, newTodo]), setUser({ ...user, name }).

Lifting state up

When two components need the same data, keep the state in their closest common parent and pass it down as props.

Props vs state

PropsState
come from the parentowned by the component
read-onlychanged with a setter
like function argumentslike the component's memory

Example

JavaScript
import { useState } from "react";

function TodoItem({ todo, onToggle }) {
  return (
    <li
      onClick={() => onToggle(todo.id)}
      style={{ textDecoration: todo.done ? "line-through" : "none", cursor: "pointer" }}>
      {todo.text}
    </li>
  );
}

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

  const toggle = (id) =>
    setTodos((list) => list.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));

  return (
    <ul>
      {todos.map((t) => <TodoItem key={t.id} todo={t} onToggle={toggle} />)}
    </ul>
  );
}
// 💻 Run in a Vite + React project