Write React Code Like a Pro: Top Practices No One Will Tell You (Except me!)
You can build high-quality, maintainable, and scalable React apps by following these best practices.
Ever wondered how the smooth, interactive interfaces of your favorite apps tick? React, the JavaScript library, is often working its magic behind the scenes!
But mastering React takes more than just knowing the basics.
To truly dominate the UI game, you need to follow these ninja-approved best practices
1. Use Functional components
Replace complex class components with functional components and hooks.
They’re leaner, and meaner, and will make your code pop.
Hooks also allow you to access state and other React features without having to use classes.
Instead of using a class component such as this:
class MyComponent extends React.Component {
state = {
count: 0
};
handleClick = () => {
this.setState({ count: this.state.count + 1 });
}; render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
We can use a functional component with the useState hook in the following way:
function MyComponent() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<p>{count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
2. Make use of JSX for rendering.
This magical syntax lets you to create HTML-like structures from within your JavaScript code.
It’s like having superpowers to create UI components!
Remember to use key rules, such as camelCase for props and unique keys for lists.
E.g., instead of this:
const items = [
{ name: "item 1", id: 1 },
{ name: "item 2", id: 2 },
{ name: "item 3", id: 3 }
];
const list = items.map((item, index) => (
<li key={index}>{item.name}</li>
));
We can use one-of-a-kind keys like this:
const items = [
{ name: "item 1", id: 1 },
{ name: "item 2", id: 2 },
{ name: "item 3", id: 3 }
];
const list = items.map(item => (
<li key={item.id}>{item.name}</li>
));
3. Keep the same naming scheme.
Consistency is important, and this goes to naming your components and functions.
Stick to a consistent style, such as PascalCase for components and camelCase for functions and variables.
You’ll thank yourself later when your code reads like a lovely poem.
4. Divide your app into small, reusable components.
Do not become caught down with bulky components.
Break your software into separated, reusable components that focus on different activities.
This makes your code modular, adaptable, and easy to maintain.
Think of it like building with Legos, but much cooler!
5. Use useful lifecycle methods.
React components go through many phases throughout their life.
Use the right lifecycle methods to carry out particular activities at each level.
componentDidMount for data fetching, componentDidUpdate for state updates, and so on. It is all about time!
6. Make use of effective error handling.
Nobody loves buggy apps.
Use try-catch statements or the excellent ErrorBoundary component to gracefully handle problems and give a nice fallback for users.
Do not let crashes ruin their experience! ️
For example —, instead of this:
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
fetch("https://myapi.com/data")
.then((response) => response.json())
.then((data) => setData(data));
}, []);
if (!data) {
return <div>Loading...</div>;
}
return <div>{data.name}</div>;
}
You can use a try-catch statement like this:
function MyComponent() {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
fetch("https://myapi.com/data")
.then((response) => response.json())
.then((data) => setData(data))
.catch((error) => setError(error));
}, []);
if (error) {
return <div>Error: {error.message}</div>;
}
if (!data) {
return <div>Loading...</div>;
}
return <div>{data.name}</div>;
}
Another option is to use the ‘ErrorBoundary’ component, which lets you handle errors that happen in a specific area of your app:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
function MyComponent() {
return (
<ErrorBoundary>
<MyComponentThatMightError />
</ErrorBoundary>
);
}
Final Words
These are just guidelines, not handcuffs!
Use your decision and adapt as your project develops.
And keep learning, because React is always growing and getting better.
Don’t exit without a $1 coffee gift to boost me for more content!