As with any framework, React comes with its own set of best practices and optimal patterns. Let’s explore some tips for writing robust React code:
Modular Components
Break components into reusable, composable units:
// Bad
function App() {
return (
<header>
<nav>
<logo>
<links>
</nav>
<h1>Welcome!</h1>
<footer>
<copyright>
</footer>
</header>
);
}
// Good
function Nav() {
return (
<nav>
<Logo />
<Links />
</nav>
);
}
function Header() {
return (
<header>
<Nav />
<h1>Welcome!</h1>
<Footer />
</header>
);
}
This encourages reusability.
Unidirectional Data Flow
Follow the one-way data flow paradigm:
- State is passed down as props
- Events bubble up to trigger state changes
This prevents cascading updates across components.
Strict Mode
Enable Strict Mode during development to catch common issues:
// index.js
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Strict mode checks for deprecated lifecycles, unsafe practices, and more.
ESLint & Prettier
Use ESLint and Prettier to enforce consistent code style. Common plugins include:
eslint-plugin-react
eslint-plugin-jsx-a11y
(accessibility checks)eslint-plugin-react-hooks
Summary
- Modular components for reusability
- Unidirectional data flow
- Strict Mode for catching issues
- ESLint & Prettier for consistent style
Following React best practices leads to apps that are scalable, robust and maintainable.