React Patterns
HOC - higher Order Components
-
What it is: This is a function that takes a component as an argument and returns a new, enhanced component. It’s like wrapping your component in a fancy new outfit that gives it superpowers.
-
Why it’s hot: Perfect for sharing common logic or props across multiple components without repeating yourself. Think authentication, data fetching, or even just adding some styling.
Render props
- What it is: Instead of a HOC, here you pass a function as a prop to a component. This function then dictates what the component should render. It gives the consuming component control over what’s rendered, while the parent component manages the state or logic.
- Why it’s hot: Another fantastic way to share code between components, especially when you need more flexibility in rendering than HOCs might provide. It’s great for things like mouse tracking, data fetching, or any kind of stateful logic you want to reuse.
- Example: A
<Mouse position={({ x, y }) => <p>Mouse is at: {x}, {y}</p>} />component.
Custom Hooks
- What it is: With a hook you can extract stateful logic from a component into a reusable function. It’s like having your own little helper function that knows how to manage state and side effects. Why it’s hot: Custom Hooks are incredibly powerful. They make your code cleaner, easier to test, and much more readable than HOCs or render props for many use cases. They let you share logic without changing your component hierarchy. Example: A useFormInput hook to handle the state and validation of form inputs, or a useFetch hook for data fetching.
Context API
- What it is: This is React’s built-in solution for “prop drilling” (passing props down through many levels of components). It allows you to make data available to any component in the tree without explicitly passing it down as props.
- Why it’s hot: Great for global data like themes, user authentication status, or locale settings. Use it sparingly though, as it can make components less self-contained if overused.
- Example: A ThemeContext that provides dark or light mode settings to any component that needs it.