Compound & HOC

Preview — 3 of 10 questions

What is the Render Props pattern?

javascript
// MouseTracker using render props:
function MouseTracker({ render }) {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  const handleMouseMove = (e) => setPosition({ x: e.clientX, y: e.clientY });

  return (
    <div onMouseMove={handleMouseMove}>
      {render(position)} {/* consumer controls what renders */}
    </div>
  );
}

// Usage:
<MouseTracker
  render={({ x, y }) => <Circle x={x} y={y} />}
/>
<MouseTracker
  render={({ x, y }) => <Crosshair x={x} y={y} />}
/>
ARender props require class components to work
BThe render prop function must return a string
CRender Props is a pattern where a component receives a function prop that it calls with its internal state — the function returns JSX; this inverts control to the consumer for rendering while the component owns behavior
DRender Props and HOCs are the same pattern with different syntax

What is the HOC pattern?

javascript
// HOC: function that takes a component, returns an enhanced component
function withAuth(WrappedComponent) {
  return function AuthenticatedComponent(props) {
    const { user, isLoading } = useAuth();

    if (isLoading) return <Spinner />;
    if (!user) return <Redirect to="/login" />;

    return <WrappedComponent {...props} user={user} />;
  };
}

// Usage:
const ProtectedDashboard = withAuth(Dashboard);
const ProtectedProfile   = withAuth(Profile);
AHOCs can only wrap one component at a time
BA HOC is a function that takes a component and returns a new component with added behavior — useful for cross-cutting concerns (authentication, logging, analytics) applied to many components
CHOCs cannot pass props to the wrapped component
DHOCs are deprecated and should never be used in new code

What distinguishes controlled from uncontrolled?

javascript
// Controlled — React owns state:
function ControlledInput() {
  const [value, setValue] = useState("");
  return (
    <input
      value={value}
      onChange={e => setValue(e.target.value)}
    />
  );
}

// Uncontrolled — DOM owns state:
function UncontrolledInput() {
  const ref = useRef(null);
  const handleSubmit = () => {
    console.log(ref.current.value); // read DOM value on demand
  };
  return <input ref={ref} defaultValue="" />;
}
AControlled: React state drives the input value — enables instant validation, format-as-you-type, conditional disabling; Uncontrolled: DOM manages state — simpler for simple forms, avoids re-renders on each keystroke
BUncontrolled components are always faster
CYou can mix controlled and uncontrolled modes for the same input at runtime
DdefaultValue and value are interchangeable

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.