Reusable Components Flashcards
What is the purpose of generic type parameters in TypeScript functions?
They allow flexibility by enabling the function to work with different data types, defined within angled brackets.
How are generic types defined in TypeScript?
By using a type alias with generic parameters in angled brackets, e.g., type TypeName<T1, T2> = { ... };
.
How do you define generic props for a React component?
Use generic type parameters in the props definition, e.g., type Props<Item> = { items: Item[]; };
.
How do you make a React component reusable with generics?
By using generic props within the component, e.g., export function List<Item>({ items }: Props<Item>) { ... }
.
What is props spreading in React?
It is the process of passing all the props of an HTML element to a component, using the rest parameter and spreading them.
What does ComponentPropsWithoutRef
do in React?
It references the props of an HTML element (e.g., ul
), allowing you to pass them as props to a component.
It references the props of an HTML element (e.g., ul
), allowing you to pass them as props to a component.
Render props allow a prop (other than children) to be a function that renders elements, making components more reusable.
When would you use render props in React?
When the children prop is already in use and you want to pass a function for rendering elements, often for data-driven lists.
Provide an example of using render props in React.
<List data={[...]} renderItem={(item) => <div>{item.text}</div>} />
What are custom hooks in React?
Functions that start with use, return an object structure, and can accept parameters or use other React hooks.
Why are custom hooks useful in React?
They isolate logic, making it reusable across components.
How do custom hooks help with code reuse?
By encapsulating reusable logic, such as state management or side effects, and returning values in an object format.
What is the naming convention for custom hooks in React?
Custom hooks must start with the prefix use, helping ESLint identify them as hooks.
Provide an example of a custom hook in React.
export function useToggle() { const [toggleValue, setToggleValue] = useState(false); function toggle() { setToggleValue(!toggleValue); } return { toggleValue, toggle }; }
What is a common use case for render props in React?
Data-driven lists where the rendering of list items can be customized by passing a function to the renderItem prop.