Skip to content

Coding best practices

Vlad Volkov edited this page Jan 25, 2022 · 1 revision

Frontend

React Components

  • Functional or class components should be named in UpperCamelCase convention:
import { FC } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card } from 'antd'

type SectionProps = {
  url: string
}

const Section : FC<SectionProps> = ({ url = "" }) => {
  const navigate = useNavigate()

  return <Card onClick={() => navigate(url)} />
}
  • Use suffixes for sibling entities related to root one: Props, Provider, Fragment
type ModalProps = {
  visible: boolean
}

const defaultValue : ModalProps = { visible: false } 

const ModalContext = createContext(defaultValue)

const Modal : FC = () => {
  return <ModalContext.Consumer>{({ visible })} => <div style={{ display: visible ? "initial" : "none" } />}</ModalContext.Consumer>
}
  • Use aliases when wrapping component with same name to keep same name as original one.
import { Modal as Wrapped } from 'antd'

// Using type extension to enhance wrapped component with new props
type ModalProps = typeof Wrapped.defaultProps & {
  opacity: number
}

// Using Partial in-place to make all properties optional in one place
const Modal: FC<Partial<ModalProps>> = props => {
  // Using with destructuring assignment to separate new properties from origin
  const { children, opacity, className, style, ...modalProps } = props
  // Have to extract styles and class name to merge with enhanced
  return (
    <Wrapped className={[className, 'modal-opaque'].join(' ')} style={{ ...style, opacity }} {...modalProps}>
      {children}
    </Wrapped>
  )
}
  • Custom hooks should be named in lowerCamelCase with use prefix:
function useCustomHook() {
  return { message: "Message from the void" }
}
  • Custom HOCs should be named in lowerCamelCase with with prefix:
function withScrollToTop<T>(Wrapped: FC<T>): FC<T> {
  return (props) => {
    const { pathname } = useLocation();
  
    useLayoutEffect(() => {
      window.scrollTo(0, 0);
    }, [pathname]);

    return <Wrapped {...props} />
  }
}
Clone this wiki locally