Components & Props
EasyComponents are the building blocks of React applications. They are JavaScript functions that accept props as input and return JSX describing what should appear on screen. Props flow one way from parent to child, creating a predictable data flow.
Interactive Visualization
Key Points
- Components are functions that return JSX
- Props are read-only and flow from parent to child
- Component names must start with an uppercase letter
- Props should be typed with a dedicated interface
- Default props can be set via destructuring defaults
- Props are the mechanism for component reusability and configuration
- Prop changes trigger a re-render of the component
Code Examples
Typed Component with Props
interface ButtonProps { label: string variant?: 'primary' | 'secondary' onClick: () => void disabled?: boolean } function Button({ label, variant = 'primary', onClick, disabled = false, }: ButtonProps) { return ( <button className={variant} onClick={onClick} disabled={disabled} > {label} </button> ) } // Usage <Button label="Save" onClick={handleSave} /> <Button label="Cancel" variant="secondary" onClick={handleCancel} />
Props are typed with an interface and destructured in the function signature with optional defaults
Passing Data Down
interface User { id: string name: string email: string } interface UserProfileProps { user: User } function UserProfile({ user }: UserProfileProps) { return ( <div> <Avatar name={user.name} /> <UserDetails name={user.name} email={user.email} /> </div> ) } function Avatar({ name }: { name: string }) { return <div>{name[0]}</div> } function UserDetails({ name, email }: { name: string; email: string }) { return ( <div> <h2>{name}</h2> <p>{email}</p> </div> ) }
Data flows down from parent to child through props, each component receiving only the data it needs
Common Mistakes
- Mutating props directly instead of treating them as read-only
- Passing too many individual props when an object prop would be cleaner
- Not providing TypeScript interfaces for component props
Interview Tips
- Explain the one-way data flow and why React enforces it
- Discuss when to lift state up versus use context to avoid prop drilling
- Know the difference between props and state