Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

hoc-pattern

БесплатноБез исполняемых скриптовНе проверен

Teaches the Higher-Order Component (HOC) pattern for logic reuse. Use when you need to share cross-cutting concerns like authentication, logging, or data…

PatternsDevот PatternsDev★ 261 звезда на GitHub

Об этом скилле

HOC Pattern

Table of Contents

Within our application, we often want to use the same logic in multiple components. This logic can include applying a certain styling to components, requiring authorization, or adding a global state.

One way of being able to reuse the same logic in multiple components, is by using the higher order component pattern. This pattern allows us to reuse component logic throughout our application.

When to Use

  • Use this when the same uncustomized behavior needs to be applied to many components
  • This is helpful when a component should work standalone without the added custom logic

When NOT to Use

  • When custom hooks can achieve the same result with less nesting and better readability
  • In new React 18+ code where hooks are the idiomatic approach to sharing stateful logic
  • When the HOC wrapper adds prop-name collisions or obscures the component tree in DevTools

Instructions

  • Create a function that takes a component and returns a new component with enhanced behavior
  • Avoid naming collisions by renaming or merging props in the HOC
  • Prefer React Hooks over HOCs for most new code to avoid wrapper hell and deep nesting
  • Compose multiple HOCs carefully and be aware that the order of composition matters

Details

A Higher Order Component (HOC) is a component that receives another component. The HOC contains certain logic that we want to apply to the component that we pass as a parameter. After applying that logic, the HOC returns the element with the additional logic.

Say that we always wanted to add a certain styling to multiple components in our application. Instead of creating a style object locally each time, we can simply create a HOC that adds the style objects to the component that we pass to it:

function withStyles(Component) {
  return props => {
    const style = { padding: '0.2rem', margin: '1rem' }
    return <Component style={style} {...props} />
  }
}

const Button = () => <button>Click me!</button>
const Text = () => <p>Hello World!</p>

const StyledButton = withStyles(Button)
const StyledText = withStyles(Text)

We just created a StyledButton and StyledText component, which are the modified versions of the Button and Text component. They now both contain the style that got added in the withStyles HOC!

Let's improve the user experience a little bit. When we're fetching the data, we want to show a "Loading..." screen to the user. Instead of adding data to the DogImages component directly, we can use a Higher Order Component that adds this logic for us.

Let's create a HOC called withLoader. A HOC should receive a component, and return that component. In this case, the withLoader HOC should receive the element which should display Loading… until the data is fetched.

function withLoader(Element) {
  return (props) => <Element />;
}

However, we don't just want to return the element it received. Instead, we want this element to contain logic that tells us whether the data is still loading or not.

To make the withLoader HOC very reusable, we won't hardcode the Dog API url in that component. Instead, we can pass the URL as an argument to the withLoader HOC, so this loader can be used on any component that needs a loading indicator while fetching data from a different API endpoint.

function withLoader(Element, url) {
  return (props) => {};
}

A HOC returns an element, a functional component props => {} in this case, to which we want to add the logic that allows us to display a text with Loading… as the data is still being fetched. Once the data has been fetched, the component should pass the fetched data as a prop.

We just created a HOC that can receive any component and url.

  1. In the useEffect hook, the withLoader HOC fetches the data from the API endpoint that we pass as the value of url. While the data hasn't returned yet, we return the element containing the Loading... text.
  2. Once the data has been fetched, we set data equal to the data that has been fetched. Since data is no longer null, we can display the element that we passed to the HOC!

So, how can we add this behavior to our application? In DogImages.js, we no longer want to just export the plain DogImages component. Instead, we want to export the "wrapped" withLoading HOC around the DogImages component.

export default withLoader(
  DogImages,
  "https://dog.ceo/api/breed/labrador/images/random/6"
);

The Higher Order Component pattern allows us to provide the same logic to multiple components, while keeping all the logic in one single place. The withLoader HOC doesn't care about the component or url it receives: as long as it's a valid component and a valid API endpoint, it'll simply pass the data from that API endpoint to the component that we pass

Полный SKILL.md на GitHub

Установить hoc-pattern в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл hoc-pattern?

Teaches the Higher-Order Component (HOC) pattern for logic reuse. Use when you need to share cross-cutting concerns like authentication, logging, or data fetching across multiple components.

Как установить скилл hoc-pattern?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл hoc-pattern запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить hoc-pattern с