reactjs
/

React Best Practices – Writing Clean & Scalable Code

Last Sync: Today

On this page

6
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

reactjs

React Best Practices – Writing Clean & Scalable Code

The Philosophy of Clean React

Writing React code that works is easy; writing React code that is maintainable, testable, and performant in a team environment is the real challenge. In 2026, best practices revolve around functional programming, declarative UI, and strict separation of concerns.

  1. Component Composition & Small Components

Avoid 'God Components'—huge files that handle everything. Break UI into small, reusable pieces. If a component exceeds 150 lines or handles more than one responsibility, it's time to split it.

  • Single Responsibility: One component should do one thing (e.g., a Button, a UserCard, or a Form).
  • Composition over Inheritance: Use the children prop to create flexible layouts instead of complex prop configurations.
  • Extract Logic: Move complex business logic out of JSX and into Custom Hooks.

  1. State Management Principles

Mismanaged state is the #1 cause of bugs and performance issues. Keep state as local as possible and only lift it up when absolutely necessary.

React JSXRead-only
1
// ❌ Bad: Keeping everything in global state
const { tempInputValue } = useSelector(state => state.ui);

// ✅ Good: Keep UI-only state local to the component
const [tempValue, setTempValue] = useState('');

  1. The Power of Custom Hooks

Custom hooks are the best way to share logic between components. If you find yourself writing the same useEffect or useState logic in two places, abstract it.

React JSXRead-only
1
// useWindowSize.js
export function useWindowSize() {
  const [size, setSize] = useState(window.innerWidth);
  useEffect(() => {
    const handleResize = () => setSize(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  return size;
}

  1. Defensive Coding & Security

  • Optional Chaining: Use user?.profile?.name to avoid 'cannot read property of undefined' crashes.
  • Prop Types / TypeScript: Always define the shape of your props to catch bugs at compile-time.
  • Sanitize Data: Never use dangerouslySetInnerHTML with unsanitized user input to prevent XSS attacks.

Best Practice Comparison

AreaOld Way (Avoid)Modern Way (2026)
LogicMixed in Component bodyAbstracted into Custom Hooks
API CallsInside every componentCentralized services + React Query
StylingGlobal CSS filesTailwind CSS or CSS Modules
PropsDeep Prop DrillingContext API or State Libraries
UpdatesDirect State MutationFunctional updates: `set(c => c + 1)`

Try it yourself

import React, { useState, useEffect } from 'react';

// BEST PRACTICE: Separate Logic into a Custom Hook
function useCounter(initial = 0) {
  const [count, setCount] = useState(initial);
  const increment = () => setCount(prev => prev + 1);
  const decrement = () => setCount(prev => prev - 1);
  return { count, increment, decrement };
}

// BEST PRACTICE: Descriptive, Small Component
const CounterDisplay = ({ value }) => (
  <h2 style={{ color: value < 0 ? 'red' : 'green' }}>
    Value: {value}
  </h2>
);

export default function BestPracticesApp() {
  const { count, increment, decrement } = useCounter(10);

  return (
    <div style={{ padding: '20px', textAlign: 'center' }}>
      <h3>Clean Code Demo</h3>
      <CounterDisplay value={count} />
      <button onClick={decrement}>-</button>
      <button onClick={increment} style={{ marginLeft: '10px' }}>+</button>
      <p>Logic is separated, UI is composed!</p>
    </div>
  );
}

Test Your Knowledge

Q1
of 2

What is the primary benefit of 'Composition' in React?

A
It makes the code run faster
B
It allows components to be more flexible and reusable by nesting
C
It replaces the need for state
D
It hides the source code
Q2
of 2

Why should you use functional updates like 'setCount(c => c + 1)'?

A
It is less code to write
B
It ensures you are working with the most current state value
C
It prevents the component from rendering
D
It is required by TypeScript

Frequently Asked Questions

Is it okay to use 'index' as a key in a list?

Only if the list is static and never changes. If you add, remove, or sort items, using the index will cause rendering bugs. Always use a unique ID from your data.

Should I use functional components exclusively?

Yes, unless you need an Error Boundary, which currently requires a Class Component. Functional components with Hooks are the modern standard.

Previous

react error boundaries

Next

react folder structure

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.