React Tutorial: Practical Code Examples for Developers
React has become the industry standard for building dynamic user interfaces. By focusing on a component-based architecture, it allows developers to create reusable, maintainable, and highly performant web applications. This tutorial provides a hands-on approach to understanding the core pillars of modern React development.
Understanding React Components
At the heart of every React application are components. A component is essentially a JavaScript function that returns JSX (JavaScript XML), a syntax extension that looks like HTML but allows you to inject dynamic logic directly into your UI.
Creating Your First Functional Component
Modern React relies almost exclusively on functional components. Here is a simple example of a reusable button component:
function ActionButton({ label, onClick }) {
return (
<button onClick={onClick} className="btn-primary">
{label}
</button>
);
}
By using props (short for properties), you can pass data into components, making them flexible and reusable across your application.
Managing Local State with useState
State is how a component keeps track of information that changes over time. The useState hook is the standard way to manage this data within a functional component.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Current count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
When setCount is called, React automatically re-renders the component to reflect the updated value in the browser.
Handling Side Effects with useEffect
Often, your components need to interact with the outside world—fetching data from an API, setting up subscriptions, or manually changing the DOM. The useEffect hook handles these "side effects."
import { useEffect, useState } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(json => setData(json));
}, []); // Empty array means this runs only once on mount
return <div>{data ? data.title : 'Loading...'}</div>;
}
Best Practices for Scalable Code
As your application grows, maintaining clean code becomes critical. Follow these best practices to ensure your React project remains manageable:
- Keep Components Small: If a component exceeds 100 lines, consider breaking it into smaller sub-components.
- Lift State Up: If two components need the same data, store that state in their common parent and pass it down via props.
- Avoid Prop Drilling: If you find yourself passing props through multiple layers of components, consider using the Context API or a state management library like Zustand or Redux.
- Use Meaningful Names: Name your components and props based on their purpose rather than their implementation details.
Common Mistakes to Avoid
Even experienced developers encounter pitfalls. One common mistake is mutating state directly. Always use the setter function provided by useState to ensure React detects the change and triggers a re-render.
Another frequent error is defining functions inside the component body that are recreated on every render. Use useCallback to memoize functions if they are passed as props to optimized child components.
Conclusion
React is a powerful tool for building modern interfaces, but mastering it requires understanding the lifecycle of components and how data flows through your application. By practicing with useState, useEffect, and component composition, you will be well-equipped to build production-ready software. Start by building a small project, such as a to-do list or a weather dashboard, to put these concepts into practice.
Frequently Asked Questions
What is the difference between props and state?
Props are read-only data passed into a component from its parent, while state is internal data managed within the component itself that can change over time.
Do I need to learn class components?
No. While legacy codebases use class components, modern React development focuses on functional components and hooks. It is only necessary to learn classes if you are maintaining older projects.
When should I use useEffect?
Use useEffect for any operation that interacts with the browser API, external data sources, or timers. Avoid using it for logic that can be calculated directly during the render process.