DEV Community


Discussion on: React Best Practices

lukeshiru profile image
△ LUKE知る

Nice article. I specially agree with the part about using Functional Components instead of classes. I could argue that instead of "React best practices" this could be titled just "React Practices", because some of the practices mentioned here might be consider bad on some environments, but I'll just focus in the TS example.

First, ideally you should have the props in an external file, something like ButtonProps.ts. Also you can extend the native button, making it way more useful (JSX.IntrinsicElements["button"]):

export type ButtonProps = JSX.IntrinsicElements["button"] & {
  primary?: boolean;
Enter fullscreen mode Exit fullscreen mode

Second, you can use FC from react to have better types:

import type { FC } from "react";
import type { ButtonProps } from "./ButtonProps";
import classnames from "classnames";

export const Button: FC<ButtonProps> = ({
  primary = false,
}) => (
    className={classnames({ primary }, className)}
Enter fullscreen mode Exit fullscreen mode

The more you "extend the native elements", the more predictable and easy to use your components are. Ideally you should also use stuff like memo and forwardRef as well :D