Advanced guides

Description test


Compound Pattern

Example of complext component

Higher-Order Components (HOC)

Higher-order components are not commonly used in modern React code.

One way of being able to reuse the same logic in multiple components, is by using the higher order component pattern.

If we want to apply a certain styling to components, requiring authorization, or adding a global state.

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.

In some cases, we can replace the HOC pattern with React Hooks.

Example:

const withAuth = <P extends Record<string, unknown>>(
  Component: React.ComponentType<P>
): React.FC<P> => {
  const Auth: React.FC<P> = (props) => {
    const router = useRouter();
    const { status } = useSession({
      required: true,
      onUnauthenticated() {
        router.push("/welcome/login");
      },
    });

    if (status === "loading") {
      return "Loading ...";
    }

    return <Component {...props} />;
  };

  return Auth;
};

export default withAuth;
function DashboardPage() {
  const user = useUser();
  return <div>Hello Admin</div>;
}

export default withAuth(Control);

Custom hooks

function useKeyPress(targetKey) {
  const [keyPressed, setKeyPressed] = React.useState(false);

  function handleDown({ key }) {
    if (key === targetKey) {
      setKeyPressed(true);
    }
  }

  function handleUp({ key }) {
    if (key === targetKey) {
      setKeyPressed(false);
    }
  }

  React.useEffect(() => {
    window.addEventListener("keydown", handleDown);
    window.addEventListener("keyup", handleUp);

    return () => {
      window.removeEventListener("keydown", handleDown);
      window.removeEventListener("keyup", handleUp);
    };
  }, []);

  return keyPressed;
}

React Portals

React Portals allow for child components to be rendered into a DOM node that exists outside the usual parent-child hierarchy, essentially enabling a child to break out of its DOM tree. This is particularly useful for UI elements that need to visually ‘break out’ of their parent container, such as modals, dropdowns, or tooltips.

https://react.dev/reference/react-dom/createPortal