Intern / FresherReact

What is the difference between props and state in React?

Quick answer

Props are read-only inputs passed from a parent component, while state is data a component owns and can change over time, which triggers a re-render when updated.

Props make a component reusable: the parent decides the values, and the child must not modify them. State is private memory for a component, created with useState or useReducer. Updating state tells React to re-render that component with the new value.

A good rule is to keep state as low as possible in the tree, and lift it up to the closest common parent only when two components need to share it. Data that can be calculated from props or state should be computed during render and not stored in extra state.

function Counter({ step }) {            // step is a prop (read-only)
  const [count, setCount] = useState(0);    // count is state (owned here)
  return <button onClick={() => setCount(count + step)}>{count}</button>;
}

<Counter step={5} />

Key points

  • Props flow down, are read-only and come from the parent
  • State is owned by the component and changes cause re-renders
  • Derived values should be calculated, not stored in state
  • What is the virtual DOM in React and how does it work?

    The virtual DOM is a lightweight JavaScript copy of the UI that React compares with the previous version after each update, so it only changes the parts of the real DOM that actually differ.

  • What are React hooks and what are the rules of hooks?

    Hooks are functions such as useState and useEffect that let function components use state, lifecycle behaviour and other React features; they must be called at the top level of a component or custom hook, never inside loops, conditions or nested functions.

  • How does useEffect work in React and what is the dependency array?

    useEffect runs a function after the component renders; the dependency array tells React when to re-run it: with no array it runs after every render, with an empty array only after the first, and with values only when those values change.

  • Why do we need keys in React lists?

    Keys give each list item a stable identity so React can match items between renders and correctly add, remove or reorder them without recreating or mixing up their state.