[{"data":1,"prerenderedAt":120},["ShallowReactive",2],{"qa-\u002Freact\u002Fcomponents\u002Fprops-component-types":3},{"page":4,"siblings":99,"blog":117},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":20,"order":12,"path":21,"questions":22,"questionsCount":89,"related":90,"seo":91,"seoDescription":92,"stem":93,"subtopic":94,"topic":95,"topicSlug":96,"updated":97,"__hash__":98},"qa\u002Freact\u002Fcomponents\u002Fprops-component-types.md","Props Component Types",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"easy","md","React","react",{"subtopicSlug":19},"props-component-types",true,"\u002Freact\u002Fcomponents\u002Fprops-component-types",[23,27,31,35,40,44,48,52,56,60,64,68,72,76,80,84],{"id":24,"difficulty":14,"q":25,"a":26},"what-are-props","What are props in React?","**Props** (short for properties) are the mechanism React uses to pass data\n**down** from a parent component to a child. They are received by the child\nas a plain JavaScript object and are **read-only** — a component must never\nmodify its own props.\n\n```jsx\n\u002F\u002F Parent passes props\n\u003CGreeting name=\"Alice\" age={30} isAdmin \u002F>\n\n\u002F\u002F Child receives them\nfunction Greeting({ name, age, isAdmin }) {\n  return \u003Cp>{name} ({age}) — {isAdmin ? 'Admin' : 'User'}\u003C\u002Fp>\n}\n```\n\nProps can be any JavaScript value: strings, numbers, booleans, objects,\narrays, or even functions and React elements. Whatever you put between\nopening and closing tags flows in as `children`.\n\n**Rule of thumb:** props flow down, never up. If a child needs to\ncommunicate to its parent, pass a callback function as a prop.\n",{"id":28,"difficulty":14,"q":29,"a":30},"props-immutable","Are props mutable inside a component? Why not?","No. Props are **read-only** in React by design. A component is a pure\nfunction of its props (and state): given the same inputs it should always\nproduce the same output.\n\n```jsx\nfunction Badge({ count }) {\n  \u002F\u002F ❌ Never do this\n  count = count + 1\n\n  \u002F\u002F ✅ Derive a new value without mutating\n  const displayCount = count > 99 ? '99+' : count\n  return \u003Cspan>{displayCount}\u003C\u002Fspan>\n}\n```\n\nIf you try to reassign a prop it may work locally (it's just a JS variable),\nbut the change won't persist across renders and will confuse React's\nreconciler because the parent still owns the original value.\n\n**Rule of thumb:** treat every prop as a `const`. To derive a modified\nvalue, create a new local variable; to change what the parent passes, fire\na callback that updates the parent's state.\n",{"id":32,"difficulty":14,"q":33,"a":34},"children-prop","What is the children prop?","`children` is the implicit prop that React populates with whatever you put\n**between** a component's JSX tags. It enables composition — parent decides\nthe shell, child slot receives arbitrary content.\n\n```jsx\nfunction Panel({ title, children }) {\n  return (\n    \u003Csection className=\"panel\">\n      \u003Ch2>{title}\u003C\u002Fh2>\n      \u003Cdiv className=\"panel-body\">{children}\u003C\u002Fdiv>\n    \u003C\u002Fsection>\n  )\n}\n\n\u002F\u002F Usage\n\u003CPanel title=\"Stats\">\n  \u003Cp>Revenue: $1,200\u003C\u002Fp>\n  \u003CChart data={data} \u002F>\n\u003C\u002FPanel>\n```\n\n`children` can be a string, a single element, an array of elements, a\nfunction (render prop), or `undefined` (nothing passed). Use\n`React.Children.count(children)` or `React.Children.toArray(children)` to\ninspect it programmatically.\n\n**Rule of thumb:** `children` is just a prop with special JSX sugar. It\nlets you build generic \"container\" components that don't need to know what\ngoes inside them.\n",{"id":36,"difficulty":37,"q":38,"a":39},"function-vs-class","medium","What is the difference between a function component and a class component?","| | Function component | Class component |\n|---|---|---|\n| Syntax | Plain JS function | `class X extends React.Component` |\n| State | `useState`, `useReducer` | `this.state` \u002F `this.setState` |\n| Lifecycle | `useEffect` | `componentDidMount`, `componentDidUpdate`, etc. |\n| Context | `useContext` | `static contextType` \u002F `Context.Consumer` |\n| `this` | Not applicable | Required for everything |\n| Error boundaries | Not supported | `componentDidCatch` |\n\n```jsx\n\u002F\u002F Function component\nfunction Counter() {\n  const [n, setN] = useState(0)\n  return \u003Cbutton onClick={() => setN(n + 1)}>{n}\u003C\u002Fbutton>\n}\n\n\u002F\u002F Class component — equivalent\nclass Counter extends React.Component {\n  state = { n: 0 }\n  render() {\n    return \u003Cbutton onClick={() => this.setState({ n: this.state.n + 1 })}>{this.state.n}\u003C\u002Fbutton>\n  }\n}\n```\n\nSince React 16.8 (hooks), function components can do everything class\ncomponents can except implement error boundaries. New code should use\nfunction components.\n\n**Rule of thumb:** always write function components. Only reach for a class\nwhen you need a `componentDidCatch` error boundary — or when you're\nmaintaining legacy code.\n",{"id":41,"difficulty":37,"q":42,"a":43},"when-class-component","Is there any reason to use a class component in modern React?","The only built-in feature class components have that function components\nlack is the ability to serve as an **error boundary** via\n`componentDidCatch` and `getDerivedStateFromError`. There is no hooks-based\nequivalent in React itself (as of 2024).\n\n```jsx\nclass ErrorBoundary extends React.Component {\n  state = { hasError: false }\n\n  static getDerivedStateFromError() {\n    return { hasError: true }\n  }\n\n  componentDidCatch(err, info) {\n    logError(err, info)\n  }\n\n  render() {\n    return this.state.hasError\n      ? \u003Cp>Something went wrong.\u003C\u002Fp>\n      : this.props.children\n  }\n}\n```\n\nIn practice most teams write a single `ErrorBoundary` class component and\nreach for third-party wrappers like `react-error-boundary` everywhere else.\n\n**Rule of thumb:** one class component per project (the error boundary).\nEverything else is a function component.\n",{"id":45,"difficulty":14,"q":46,"a":47},"default-props","How do you provide default values for props?","The modern idiomatic approach is **default parameter destructuring**:\n\n```jsx\nfunction Button({ label = 'Click me', variant = 'primary', disabled = false }) {\n  return \u003Cbutton className={variant} disabled={disabled}>{label}\u003C\u002Fbutton>\n}\n```\n\nAlternatively, you can use the `defaultProps` static property, but this is\nconsidered legacy and may be removed in a future major version:\n\n```jsx\nButton.defaultProps = {\n  label: 'Click me',\n  variant: 'primary',\n  disabled: false,\n}\n```\n\nFor TypeScript users, the destructuring approach integrates cleanly with\ntype annotations:\n\n```tsx\ntype ButtonProps = { label?: string; variant?: 'primary' | 'secondary' }\nfunction Button({ label = 'Click me', variant = 'primary' }: ButtonProps) { … }\n```\n\n**Rule of thumb:** use destructuring defaults; they're co-located with the\nparameter list and work without any React-specific API.\n",{"id":49,"difficulty":37,"q":50,"a":51},"proptypes","What is PropTypes and when would you use it?","`PropTypes` is a runtime prop validation library that ships separately\n(`prop-types` package). In development mode it logs warnings when props\nfail the declared type, catching mistakes early.\n\n```jsx\nimport PropTypes from 'prop-types'\n\nfunction Avatar({ name, size, src }) {\n  return \u003Cimg src={src} alt={name} width={size} \u002F>\n}\n\nAvatar.propTypes = {\n  name: PropTypes.string.isRequired,\n  size: PropTypes.number,\n  src: PropTypes.string.isRequired,\n}\n\nAvatar.defaultProps = { size: 48 }\n```\n\nPropTypes are stripped in production builds. The trade-off vs TypeScript:\n- **PropTypes** — runtime, no build-step, catches type mistakes at render\n  time in any JS project.\n- **TypeScript** — compile-time, catches mistakes before runtime, broader\n  coverage (not just props).\n\n**Rule of thumb:** in a TypeScript project, TypeScript alone is sufficient.\nIn a plain JS project, PropTypes are a lightweight safety net.\n",{"id":53,"difficulty":14,"q":54,"a":55},"props-vs-state","What is the difference between props and state?","| | Props | State |\n|---|---|---|\n| Owned by | Parent component | Component itself |\n| Mutable by | Parent only | The component (`setState` \u002F setter) |\n| Triggers re-render | When parent re-renders | When updated via setter |\n| Purpose | Pass data in | Track internal data that changes |\n\n```jsx\nfunction Thermometer({ unit }) {       \u002F\u002F unit is a prop — parent decides\n  const [temp, setTemp] = useState(20) \u002F\u002F temp is state — component owns it\n  return (\n    \u003Cdiv>\n      {temp}° {unit}\n      \u003Cbutton onClick={() => setTemp(t => t + 1)}>+\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\nA useful mental model: props are like function arguments; state is like\nlocal variables that persist between calls.\n\n**Rule of thumb:** if a value is determined by the outside world, it's a\nprop. If it's determined by the component itself and can change, it's state.\n",{"id":57,"difficulty":37,"q":58,"a":59},"prop-drilling","What is prop drilling and what are the alternatives?","**Prop drilling** occurs when a prop must be passed through several\nintermediate layers that don't use it — just to get it to a deeply nested\ncomponent.\n\n```jsx\n\u002F\u002F Drilling `user` through three layers that don't care about it\n\u003CApp user={user}>\n  \u003CLayout user={user}>\n    \u003CSidebar user={user}>\n      \u003CAvatar user={user} \u002F>   {\u002F* ← only Avatar actually uses it *\u002F}\n    \u003C\u002FSidebar>\n  \u003C\u002FLayout>\n\u003C\u002FApp>\n```\n\nAlternatives:\n1. **Context API** — `React.createContext` + `useContext`. Best for\n   genuinely global or cross-cutting data (theme, current user, locale).\n2. **Component composition \u002F children** — pass `\u003CAvatar user={user} \u002F>`\n   as a child instead of passing `user` through intermediaries.\n3. **State management library** — Zustand, Redux, Jotai — good when many\n   unrelated components need the same data.\n\n**Rule of thumb:** before reaching for Context, try restructuring with\ncomposition. Context adds implicit coupling; explicit props are easier to\ntrace.\n",{"id":61,"difficulty":14,"q":62,"a":63},"destructuring-props","How do you destructure props and why is it preferred?","Destructure props directly in the function signature rather than accessing\nthem via the `props` object — it's more concise and makes required fields\nobvious.\n\n```jsx\n\u002F\u002F Verbose\nfunction Card(props) {\n  return \u003Cdiv className={props.variant}>{props.children}\u003C\u002Fdiv>\n}\n\n\u002F\u002F Destructured — preferred\nfunction Card({ variant, children }) {\n  return \u003Cdiv className={variant}>{children}\u003C\u002Fdiv>\n}\n\n\u002F\u002F With defaults and rest\nfunction Card({ variant = 'default', className = '', children, ...rest }) {\n  return (\n    \u003Cdiv className={`card card-${variant} ${className}`} {...rest}>\n      {children}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Rule of thumb:** destructure all props at the function signature. For\nlarge prop objects, consider grouping related props into sub-objects\n(`position={{ x, y }}`) to keep the signature readable.\n",{"id":65,"difficulty":14,"q":66,"a":67},"handler-as-prop","How do you pass an event handler as a prop?","Pass the function **reference** as a prop, not the function call. The child\nreceives it and calls it when the event fires.\n\n```jsx\n\u002F\u002F Parent\nfunction Form() {\n  function handleSubmit(data) {\n    console.log(data)\n  }\n  return \u003CSubmitButton onSubmit={handleSubmit} label=\"Save\" \u002F>\n}\n\n\u002F\u002F Child — receives and calls the handler\nfunction SubmitButton({ onSubmit, label }) {\n  return \u003Cbutton onClick={() => onSubmit({ time: Date.now() })}>{label}\u003C\u002Fbutton>\n}\n```\n\nConvention: name callback props with the `on` prefix (`onChange`, `onClose`,\n`onSubmit`) to signal that they are event-like.\n\n**Rule of thumb:** pass function references, not calls. `onClick={handle}`\npasses the function; `onClick={handle()}` calls it immediately and passes\nits return value — almost never what you want.\n",{"id":69,"difficulty":37,"q":70,"a":71},"spread-props","What is the spread-props pattern and when should you use it?","Spread props (`{...rest}`) forward a batch of unknown props to a child\nwithout enumerating each one. It's most useful in wrapper\u002Fadapter\ncomponents.\n\n```jsx\nfunction Input({ label, error, ...inputProps }) {\n  \u002F\u002F label and error are consumed here; everything else goes to \u003Cinput>\n  return (\n    \u003Cdiv>\n      \u003Clabel>{label}\u003C\u002Flabel>\n      \u003Cinput {...inputProps} \u002F>\n      {error && \u003Cspan className=\"error\">{error}\u003C\u002Fspan>}\n    \u003C\u002Fdiv>\n  )\n}\n\n\u002F\u002F Usage — all native \u003Cinput> attributes work without any boilerplate\n\u003CInput label=\"Email\" type=\"email\" name=\"email\" required error={errors.email} \u002F>\n```\n\n**Caution:** spreading onto DOM elements can forward non-standard props,\nwhich React will warn about. Always destructure known props first and spread\nthe remainder.\n\n**Rule of thumb:** spread `...rest` to DOM wrappers; avoid spreading the\nfull props object without filtering — it leaks internal props.\n",{"id":73,"difficulty":37,"q":74,"a":75},"pure-component","What is a pure component in React?","A **pure component** is one whose output depends only on its props (and\nstate), with no side effects during rendering. Given the same inputs it\nalways returns the same JSX — like a pure function in FP.\n\nIn class components, `React.PureComponent` adds a shallow-equality check\nin `shouldComponentUpdate`, preventing re-renders when props haven't\nchanged.\n\nIn function components, `React.memo` provides the same shallow-equality\nbail-out:\n\n```jsx\n\u002F\u002F Without memo — re-renders every time parent re-renders\nfunction Label({ text }) {\n  return \u003Cspan>{text}\u003C\u002Fspan>\n}\n\n\u002F\u002F With memo — skips re-render if text hasn't changed\nconst Label = React.memo(function Label({ text }) {\n  return \u003Cspan>{text}\u003C\u002Fspan>\n})\n```\n\n**Rule of thumb:** apply `React.memo` only to components that render\nfrequently with the same props and are measurably expensive. Premature\nmemoization adds complexity without benefit — profile first.\n",{"id":77,"difficulty":37,"q":78,"a":79},"composition-vs-inheritance","Why does React prefer composition over inheritance?","React's component model is built around **composition**: assembling behavior\nby combining components, not by extending them. The React team explicitly\nrecommends against using inheritance between components (other than extending\n`React.Component` once).\n\nComposition approaches:\n- **Children prop** — slot any content into a component.\n- **Specialized components** — make a `\u003CDialog>` and then a `\u003CAlertDialog>`\n  that renders a pre-configured `\u003CDialog>`, not one that extends it.\n- **Render props \u002F HOCs** — share logic without shared class hierarchies.\n\n```jsx\n\u002F\u002F ✅ Composition\nfunction SuccessDialog({ children }) {\n  return \u003CDialog icon=\"check\" title=\"Success\">{children}\u003C\u002FDialog>\n}\n\n\u002F\u002F ❌ Inheritance — unusual in React, actively discouraged\nclass SuccessDialog extends Dialog { … }\n```\n\n**Rule of thumb:** when you think \"I want a component like X but with Y\nchanged,\" reach for composition (wrap, extend via props, or use children)\nbefore ever reaching for class inheritance.\n",{"id":81,"difficulty":37,"q":82,"a":83},"controlled-component","What is a controlled component?","A **controlled component** is a form element whose value is **driven by\nReact state** rather than by the DOM. React is the single source of truth.\n\n```jsx\nfunction LoginForm() {\n  const [email, setEmail] = useState('')\n\n  return (\n    \u003Cinput\n      type=\"email\"\n      value={email}          \u002F\u002F state drives the displayed value\n      onChange={e => setEmail(e.target.value)}   \u002F\u002F state updated on change\n    \u002F>\n  )\n}\n```\n\nEvery keystroke calls `setEmail`, which updates state, which re-renders,\nwhich sets `value` — a tight loop. This means you can validate, transform,\nor intercept input on every change.\n\nThe alternative, **uncontrolled components**, read values from the DOM via\na ref at submission time rather than tracking each change.\n\n**Rule of thumb:** use controlled inputs when you need real-time validation\nor to format input as the user types; uncontrolled when the form is simple\nand you only need values on submit.\n",{"id":85,"difficulty":86,"q":87,"a":88},"render-props","hard","What is the render-props pattern?","A **render prop** is a prop whose value is a function, allowing one\ncomponent to delegate rendering decisions to its parent. It's a technique\nfor sharing stateful logic without hooks or HOCs.\n\n```jsx\n\u002F\u002F Provider of the logic\nfunction MouseTracker({ render }) {\n  const [pos, setPos] = useState({ x: 0, y: 0 })\n  return (\n    \u003Cdiv onMouseMove={e => setPos({ x: e.clientX, y: e.clientY })}>\n      {render(pos)}   {\u002F* call the function to get JSX *\u002F}\n    \u003C\u002Fdiv>\n  )\n}\n\n\u002F\u002F Consumer decides what to display\n\u003CMouseTracker render={({ x, y }) => (\n  \u003Cp>Mouse at {x}, {y}\u003C\u002Fp>\n)} \u002F>\n```\n\nThe `children` prop can be used the same way (and often is):\n\n```jsx\n\u003CMouseTracker>\n  {({ x, y }) => \u003Cp>Mouse at {x}, {y}\u003C\u002Fp>}\n\u003C\u002FMouseTracker>\n```\n\nIn modern code, custom hooks replace most render-prop use cases with less\nindirection.\n\n**Rule of thumb:** know the pattern for interviews; in practice, custom\nhooks are almost always cleaner.\n",16,null,{"description":11},"React props and component types interview questions — function vs class components, children, defaultProps, PropTypes, composition over inheritance, and controlled components.","react\u002Fcomponents\u002Fprops-component-types","Props and Component Types","Components","components","2026-06-23","JOU2b0dj3z8YqBLCQ001LOO430R9KMVhifMegiHzHE8",[100,104,105,109,113],{"subtopic":101,"path":102,"order":103},"JSX and Rendering","\u002Freact\u002Fcomponents\u002Fjsx-rendering",1,{"subtopic":94,"path":21,"order":12},{"subtopic":106,"path":107,"order":108},"Event Handling","\u002Freact\u002Fcomponents\u002Fevent-handling",3,{"subtopic":110,"path":111,"order":112},"Conditional Rendering","\u002Freact\u002Fcomponents\u002Fconditional-rendering",4,{"subtopic":114,"path":115,"order":116},"Lists and Keys","\u002Freact\u002Fcomponents\u002Flists-keys",5,{"path":118,"title":119},"\u002Fblog\u002Freact-props-component-types-guide","React Props and Component Types — A Complete Interview Guide",1782244100870]