Props: Passing Data
Props (short for “properties”) are how components communicate with each other. A parent component can pass information to a child component by giving them props.Reading Props
- Function Components
- Class Components
Passing Props
You can pass any type of value as a prop:Props are Immutable
Props are read-only. A component must never modify its own props:Pure Functions: React components must act like pure functions with respect to their props. Given the same props, a component should always render the same output.
Default Props
You can specify default values for props:Spreading Props
You can forward all props using the spread operator:State: Component Memory
State is private data managed within a component. Unlike props, state is created and managed by the component itself.State in Function Components
Function components use theuseState Hook:
useState returns an array with two elements:
- The current state value
- A function to update the state
State in Class Components
Class components usethis.state and this.setState():
setState is Asynchronous
State updates are batched for performance. Don’t rely on the current state value immediately after callingsetState:
ReactBaseClasses.js, setState accepts:
- An object of state variables to update
- A function that returns an object of state variables
- An optional callback that executes after the state is updated
From React Source: There is no guarantee that
this.state will be immediately updated, so accessing this.state after calling setState may return the old value. State updates may be batched together for performance.State Immutability
You should never mutate state directly. Always create new objects/arrays:Why Immutability Matters
- Detects changes easily: React can quickly check if a new object reference is different
- Determines when to re-render: React can optimize by comparing references
- Enables time-travel debugging: You can inspect previous state snapshots
- Enables concurrent features: React can safely pause and resume work
Lifting State Up
When multiple components need to share the same state, move the state to their closest common ancestor:Props vs State
If a value doesn’t change over time or doesn’t trigger re-renders, it probably shouldn’t be state. Consider using a regular variable, ref, or derived value instead.
Next Steps
Lifecycle
Learn about component lifecycle methods and effects
Hooks Overview
Explore React Hooks for state and side effects