React - Props & State

Props vs State

  • Props: read-only inputs passed from parent.
  • State: internal, mutable data managed by the component (via hooks in function components).

Try it: Counter

View source
const { useState } = React;
function Counter({ initial=0, step=1 }){
  const [count, setCount] = useState(initial);
  return (
    <div>
      <p>Count: <strong>{count}</strong></p>
      <button onClick={() => setCount(count + step)}>+{step}</button>
      <button onClick={() => setCount(count - step)} style={{marginLeft:8}}>-{step}</button>
      <button onClick={() => setCount(initial)} style={{marginLeft:8}}>Reset</button>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('try-props-state')).render(
  <>
    <Counter initial={0} step={1} />
    <Counter initial={10} step={5} />
  </>
);

Syntax primer (for newcomers)

  • const [count, setCount] = useState(0): Array destructuring returns the current value and an updater function.
  • function Counter({ initial = 0, step = 1 }): Default values for props using default parameters.
  • setCount(c => c + step): Functional update form uses the latest state value safely.

Tips

  • Never mutate state directly; always call the setter.
  • Use functional updates when the next state depends on the previous.

Vocabulary

  • Prop: Read-only input passed from parent to child.
  • State: Internal, changeable data of a component.

Checks for Understanding

  1. How do props differ from state?
  2. Why use the functional updater form like setCount(c => c + 1)?
Show answers
  1. Props are read-only inputs from parents; state is internal and mutable via setters.
  2. It avoids reading stale values when multiple updates happen in quick succession.

Exercises

  1. Add a +2 button that increments safely using two functional updates.
  2. Prevent the count from going below zero; disable the decrement button when at zero.
  3. Extract the counter label into a child component that receives count via props.