Logo

dev-resources.site

for different kinds of informations.

SOLID Principles for React / React Native Development

Published at
1/3/2025
Categories
react
reactnative
solidprinciples
reactjsdevelopment
Author
albertocabrerajr
Author
16 person written this
albertocabrerajr
open
SOLID Principles for React / React Native Development

In React development, creating components that are scalable, maintainable, and easy to extend is a fundamental goal. While the SOLID principles were initially designed for object-oriented programming by Robert C. Martin (Uncle Bob), they offer valuable guidelines that can also be effectively applied to React projects.

What are the SOLID Principles?

The SOLID principles are five design principles that aim to make software easier to understand, maintain, and extend. They are:

S – Single Responsibility Principle
O – Open/Closed Principle
L – Liskov Substitution Principle
I – Interface Segregation Principle
D– Dependency Inversion Principle

1. Single Responsibility Principle (SRP)

“A component should have only one reason to change.”

In React, this means a component or hook should handle one responsibility. Mixing UI logic with business logic makes components hard to maintain.

❌ Anti-Pattern Example:

function UserProfile() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch('/api/user').then(res => res.json()).then(setUser);
  }, []);

  return <div>{user?.name}</div>;
}
Enter fullscreen mode Exit fullscreen mode

The UserProfile component is responsible for both fetching user data and displaying it.

âś… Better Approach: Separate Concerns

function useUserData() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch('/api/user').then(res => res.json()).then(setUser);
  }, []);

  return user;
}

function UserProfile() {
  const user = useUserData();

  return <div>{user?.name}</div>;
}
Enter fullscreen mode Exit fullscreen mode

🧠 Takeaway: Separate data-fetching logic into a custom hook (useUserData) and keep the component focused on rendering.

2. Open/Closed Principle (OCP)

“Components should be open for extension but closed for modification.”

This means we should be able to extend the functionality of a component without modifying its existing code.

❌ Anti-Pattern Example:

function Button({ type }) {
  if (type === 'primary') return <button style={{ color: 'blue' }}>Primary</button>;

  if (type === 'secondary') return <button style={{ color: 'gray' }}>Secondary</button>;
}
Enter fullscreen mode Exit fullscreen mode

Adding more button types will require modifying the component, violating OCP.

âś… Better Approach: Use Props for Flexibility

function Button({ children, style }) {
  return <button style={style}>{children}</button>;
}

// Usage:
<Button style={{ color: 'blue' }}>Primary</Button>
<Button style={{ color: 'gray' }}>Secondary</Button
Enter fullscreen mode Exit fullscreen mode

🧠 Takeaway: Use props and composition to extend behavior without changing the core logic.

3. Liskov Substitution Principle (LSP)

“Child components should behave predictably when used in place of their parent components.”

When passing props, ensure they don’t introduce unexpected behavior.

❌ Anti-Pattern Example:

function InputField({ value }) {
  if (typeof value !== 'string') throw new Error('Value must be a string');
  return <input value={value} />;
}
Enter fullscreen mode Exit fullscreen mode

This component expects strict behavior, making it less reusable.

âś… Better Approach: Add Default Values

function InputField({ value = '' }) {
  return <input value={value} />;
}

// Usage:
<InputField value="Hello" />
<InputField />
Enter fullscreen mode Exit fullscreen mode

🧠 Takeaway: Components should gracefully handle various scenarios without breaking behavior.

4. Interface Segregation Principle (ISP)

“Components should not be forced to accept props they do not need.”

This principle suggests keeping your props clean and focused.

❌ Anti-Pattern Example:

function UserCard({ name, age, isAdmin }) {
  return <div>{name}</div>;
}
Enter fullscreen mode Exit fullscreen mode

The UserCard component accepts more props than it uses.

âś… Better Approach: Split Responsibilities

function UserName({ name }) {
  return <div>{name}</div>;
}

function UserAdmin({ isAdmin }) {
  return isAdmin ? <div>Admin</div> : null;
}
Enter fullscreen mode Exit fullscreen mode

🧠 Takeaway: Avoid overloaded props. Create smaller components to handle specific responsibilities.

5. Dependency Inversion Principle (DIP)

“High-level modules should not depend on low-level modules. Both should depend on abstractions.”

In React, use custom hooks or context to abstract dependencies.

❌ Anti-Pattern Example:

function UserProfile() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch('/api/user').then(res => res.json()).then(setUser);
  }, []);

  return <div>{user?.name}</div>;
}
Enter fullscreen mode Exit fullscreen mode

The component directly depends on the fetch API.

âś… Better Approach: Use Dependency Injection

function useUserService(fetcher) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetcher().then(setUser);
  }, [fetcher]);

  return user;
}

// Usage:
function UserProfile() {
  const user = useUserService(() => fetch('/api/user').then(res => res.json()));
  return <div>{user?.name}</div>;
}
Enter fullscreen mode Exit fullscreen mode

🧠 Takeaway: Abstract dependencies via hooks to make the code easier to test and maintain.


🎯 Key Takeaways

Principle Focus in React Best Practice
S – Single Responsibility Components & Hooks Keep logic
O – Open/Closed Props & Composition Extend via props, avoid modification
L – Liskov Substitution Props & Behavior Ensure predictable behavior
I – Interface Segregation Props Use focused, minimal props
D – Dependency Inversion Hooks & Context Abstract dependencies via hooks

🛠️ Final Thoughts

Applying SOLID principles in React helps create cleaner, reusable, and maintainable components. By following these guidelines, you'll improve your code's scalability and make future changes easier to manage.

solidprinciples Article's
30 articles in total
Favicon
ISP - O Princípio da Segregação de Interface
Favicon
Disadvantages of the Single Responsibility Principle(SRP)
Favicon
Guia: O que Ă© SOLID
Favicon
Interface Segregation Principle (ISP)
Favicon
Dependency Inversion Principle (DIP)
Favicon
Liskov Substitution Principle (LSP)
Favicon
Create your own Logger using Open-closed principle
Favicon
SOLID: Dependency Inversion Principle (DIP) in C#
Favicon
SOLID: Principio de Abierto/Cerrado
Favicon
LSP - O Princípio da Substituição de Liskov
Favicon
SOLID: Principio de Responsabilidad Ăšnica
Favicon
SOLID Principles for React / React Native Development
Favicon
Single Responsibility Principle (SRP)
Favicon
Solid Prensipleri
Favicon
Mastering SOLID Principles in .NET Core: A Path to Clean and Scalable Code
Favicon
OCP - O PrincĂ­pio Aberto/Fechado
Favicon
SRP - O PrincĂ­pio da Responsabilidade Ăšnica
Favicon
SOLID Design Principles
Favicon
Rethinking interfaces in Flutter projects
Favicon
Understanding the SOLID Principles in PHP and How They Improve Code Quality
Favicon
SOLID: The Liskov Substitution Principle (LSP) in C#
Favicon
Is Clean Code really practical?
Favicon
Open/Closed Principle (OCP)
Favicon
Single Responsibility Principle (SRP)
Favicon
Solid Principle in Simple English
Favicon
Why Clean Architecture and SOLID Principles Should Be the Foundation of Your Next Project!
Favicon
Seja um desenvolvedor melhor com S.O.L.I.D.
Favicon
SOLID: Open-Closed Principle (OCP) in C#
Favicon
SOLID Principles Explained in a Simple Way 🛠️✨ with Real-Life Examples
Favicon
Object Oriented Design Balance With Understanding Anti-Single Responsibility Principle

Featured ones: