SOLID Clean Code In React

TopicSource
๐Ÿงฉ ReactThis is the Only Right Way to Write React clean-code - SOLID - YouTube

SOLID principles are made for object-oriented programming languages, so they can be used in React with TypeScript.

The 5 letters stand for:

Single Responsibility
Open-closed
Liskov Substitution
Interface Segregation
Dependency Inversion

Single Responsibility

  • every class should only have one responsibility
  • don't put the logic to pull data, manipulate data and is basically just basic JS code into the same place as the React Code and JSX
  • when having a complex hook setup, consider hiding this behind a custom hook that handles useState and useEffect

Open-closed

  • software should be open for extension
  • but closed for modification
  • build your component in a way, that you don't need to modify it for every change outside
  • pass in elements from the outside as React.Nodes if you don't know what they are inside the component

Liskov Substitution

  • Subtype objects should be substitutable for supertype objects
  • pass the props of your base component through

Interface Segregation

  • components should not depend on things that they don't use
  • don't pass all the data along into other components that the component isn't using

Dependency Inversion

  • an entity should depend upon abstractions not concretions
  • make standalone baseline components that can be extended instead of modifying a component to be usable in all cases
  • pass through parts, that change in different contexts
  • or create another component, that uses the base component and adds the additional logic

  1. Pros and cons of React