These topics are perfect for beginners getting started with React:
- ⚛️ What is React? Why use React?
- 🛠️ Setting Up a React App:
- 📁 Folder Structure Basics
- ✨ JSX Syntax
- 🧩 Functional Components vs Class Components
- 🖼️ Rendering Elements
- 📦 Props (Properties)
- 🔄 State in Functional Components (
useState) - 🎯 Event Handling
- 🔀 Conditional Rendering
- 📝 Lists and Keys
- 🎨 Basic Styling (Inline CSS, CSS Modules)
React is a popular open-source JavaScript library developed by Facebook for building user interfaces, especially single-page applications (SPAs) where you need a fast, interactive user experience.
- 🧩 Component-Based: React lets you build encapsulated components that manage their own state, then compose them to make complex UIs.
- 📝 Declarative: You describe what you want the UI to look like, and React updates and renders the right components efficiently when your data changes.
- ⚡ Virtual DOM: React uses a virtual DOM to optimize updates, making UI changes fast and efficient.
- ➡️ Unidirectional Data Flow: Data flows in one direction, making it easier to understand and debug your app.
- ♻️ Reusable Components: Build small, reusable pieces of UI that can be shared and reused across your app.
- 🌐 Large Ecosystem: Huge community, lots of libraries, tools, and resources.
- 🚀 Strong Performance: Virtual DOM and efficient diffing algorithms make updates fast.
- 🧠 Easy to Learn: Simple API, especially for those familiar with JavaScript.
- 🏢 Backed by Facebook: Used in production by Facebook, Instagram, WhatsApp, and many others.
- 🔍 SEO Friendly: With tools like Next.js, React can be rendered on the server for better SEO.
import React from 'react';
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default Welcome;- 🖥️ When building interactive UIs or SPAs.
- 🧩 When you want to break your UI into reusable components.
- 🌍 When you need a large ecosystem and community support.
A well-organized folder structure makes your React project easier to scale, maintain, and collaborate on. Here’s a common and beginner-friendly structure for React apps:
my-react-app/
├── 📁 public/ # Static files (index.html, favicon, images)
├── 📁 src/ # All React code lives here
│ ├── 📁 components/ # Reusable UI components (Button, Navbar, etc.)
│ ├── 📁 pages/ # Page-level components (Home, About, etc.)
│ ├── 📁 assets/ # Images, fonts, and other static resources
│ ├── 📁 styles/ # CSS or SCSS files
│ ├── App.js # Main app component
│ ├── index.js # Entry point (renders App)
│ └── ...other files
├── package.json # Project metadata & dependencies
└── README.md # Project documentation
- 📁 public/: Contains static files. The main file is
index.htmlwhere your React app is mounted. - 📁 src/: All your JavaScript/JSX code, styles, and assets go here.
- 📁 components/: Store small, reusable UI pieces (e.g.,
Button.js,Navbar.js). - 📁 pages/: Store components that represent full pages or routes (e.g.,
Home.js,About.js). - 📁 assets/: Images, fonts, icons, etc.
- 📁 styles/: CSS, SCSS, or CSS Modules for styling your app.
- 🗂️ App.js: The root component that holds your app’s structure.
- 🗂️ index.js: The entry point that renders
<App />into the DOM.
- 📁 components/: Store small, reusable UI pieces (e.g.,
- 📦 package.json: Lists dependencies and scripts for your project.
- 📄 README.md: Project overview and instructions.
- 🧩 Separation of Concerns: Keeps code modular and easy to find.
- 🔄 Reusability: Encourages building reusable components.
- 🛠️ Scalability: Makes it easier to add new features as your app grows.
- 👥 Collaboration: Team members can quickly understand and navigate the project.
Suppose you want to add a Header component:
- 📝 Create
src/components/Header.js:import React from 'react'; function Header() { return <header>Welcome to My App!</header>; } export default Header;
- ➕ Import and use it in
App.js:import Header from './components/Header'; function App() { return ( <div> <Header /> {/* other components */} </div> ); }
JSX (JavaScript XML) is a syntax extension for JavaScript recommended by React. It looks similar to HTML and is used to describe what the UI should look like.
- 📝 Declarative: Clearly describes the UI structure.
- 💡 Expressive: Mixes HTML-like tags with JavaScript, making it powerful and flexible.
- 🛡️ Prevents Injection Attacks: Escapes values embedded in JSX, helping to prevent XSS (Cross-Site Scripting) attacks.
- 🏷️ Elements:
<div>,<span>,<h1>are JSX elements. - 🧩 Components: Custom components start with a capital letter, like
<MyComponent />. - 📝 Attributes: Use camelCase for attributes (e.g.,
classNameinstead ofclass). - 👶 Children: Elements can have children, which are passed between the opening and closing tags.
const element = <h1 className="greeting">Hello, world!</h1>;You can embed any JavaScript expression in JSX by wrapping it in curly braces {}.
const name = 'Alice';
const element = <h1>Hello, {name}!</h1>;JSX may look like HTML, but there are important differences:
- 🧮 JavaScript Expressions: You can use any JavaScript expression inside
{}. - 📝 Attributes: Use camelCase for attributes (e.g.,
classNameinstead ofclass). - 🎨 Styling: You can’t use CSS styles directly; you need to use
styleattribute with an object.
const user = { firstName: 'John', lastName: 'Doe' };
const element = <h1>Hello, {user.firstName} {user.lastName}!</h1>;- 🧩 Use Fragments: Use
<>and</>to group multiple elements without adding extra nodes to the DOM. - ✂️ Self-Closing Tags: Use self-closing tags for elements without children, like
<img />or<br />.
In React, components can be defined as functions or classes. Understanding the difference is key to mastering React.
- 🧩 Definition: JavaScript functions that return JSX.
- ✍️ Syntax: Can be written as regular functions or arrow functions.
- 🔄 State & Lifecycle: Use React hooks (e.g.,
useState,useEffect) for state and lifecycle management.
React functional components use hooks to manage lifecycle events. The most common hook for lifecycle is useEffect.
- 🟢 Mounting: Code inside
useEffectwith an empty dependency array ([]) runs once after the component mounts (likecomponentDidMount). - 🟡 Updating: Code inside
useEffectwith dependencies runs after those dependencies change (likecomponentDidUpdate). - 🔴 Unmounting: Return a cleanup function from
useEffectto run code when the component unmounts (likecomponentWillUnmount).
import React, { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(0);
// Mounting & Updating
useEffect(() => {
const timer = setInterval(() => setCount(c => c + 1), 1000);
// Unmounting (cleanup)
return () => clearInterval(timer);
}, []); // [] = only on mount/unmount
return <div>Timer: {count}</div>;
}- 🪝
useEffect: Side effects, data fetching, subscriptions, cleanup. - 🪝
useLayoutEffect: LikeuseEffectbut fires synchronously after all DOM mutations. - 🪝
useRef: Persist values across renders (like instance variables).
- 🏛️ Definition: ES6 classes that extend from
React.Component. - ✍️ Syntax: More boilerplate code, including
render()method. - 🔄 State & Lifecycle: Manage state and lifecycle methods (e.g.,
componentDidMount) directly.
Class components have built-in lifecycle methods that are called at different stages:
- 🟢 Mounting:
- 🏗️
constructor() - 🔄
static getDerivedStateFromProps() - 🖼️
render() - 🚦
componentDidMount()
- 🏗️
- 🟡 Updating:
- 🔄
static getDerivedStateFromProps() - 🔁
shouldComponentUpdate() - 🖼️
render() - 📝
getSnapshotBeforeUpdate() - 🔄
componentDidUpdate()
- 🔄
- 🔴 Unmounting:
- 🧹
componentWillUnmount()
- 🧹
⚠️ Error Handling:- 🛑
componentDidCatch() - 🛑
static getDerivedStateFromError()
- 🛑
import React, { Component } from 'react';
class Timer extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
this.timer = setInterval(() => this.setState({ count: this.state.count + 1 }), 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return <div>Timer: {this.state.count}</div>;
}
}| Phase | Class Component Method | Functional Component Hook |
|---|---|---|
| 🟢 Mount | constructor, componentDidMount | useEffect(() => {...}, []) |
| 🟡 Update | componentDidUpdate | useEffect(() => {...}, [deps]) |
| 🔴 Unmount | componentWillUnmount | useEffect(() => {... return ...}, []) |
- 🧩 Prefer Functional Components: Use hooks for lifecycle logic; they are more concise and flexible.
- 🛠️ Class Components: Still useful for legacy code or advanced error boundaries.
- 🔄 Cleanup: Always clean up subscriptions, timers, or listeners in
useEffectorcomponentWillUnmount.
Rendering elements is how React displays components on the screen. It’s a crucial concept to understand how your UI is updated and displayed.
- 🖼️ Definition: A method that tells React what to display on the screen.
- 🛠️ Usage: Used in class components to return the JSX to be rendered.
class MyComponent extends React.Component {
render() {
return <h1>Hello, world!</h1>;
}
}Functional components return JSX directly, without a render() method.
function MyComponent() {
return <h1>Hello, world!</h1>;
}React updates the rendered output when the component’s state or props change. It efficiently updates only the parts of the DOM that have changed.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}React uses a virtual DOM to optimize rendering. It keeps a lightweight copy of the actual DOM and updates it efficiently.
- 📝 Declarative: You describe what the UI should look like, and React takes care of updating the DOM.
- ⚡ Efficient: React minimizes direct manipulation of the DOM, leading to better performance.
- 🔄 Automatic Updates: The UI automatically updates when the component’s state or props change.
- ✂️ Keep Render Methods Simple: Don’t put too much logic in the render method; keep it focused on describing the UI.
- 🗝️ Use Keys in Lists: When rendering lists of elements, use unique keys to help React identify which items have changed.
Props are how you pass data from parent to child components in React. They are essential for building dynamic and interactive UIs.
- 🏷️ Definition: Short for "properties"; they are read-only attributes used to pass data and event handlers down to child components.
- 🚫 Immutable: Props are immutable from the child component’s perspective; they cannot be modified by the child.
Props are passed to components similarly to HTML attributes.
<Welcome name="Alice" />Props are accessible in the component’s props object.
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}You can define default values for your props using defaultProps.
Welcome.defaultProps = {
name: 'Guest',
};You can specify the types of props using prop-types package for better validation and documentation.
import PropTypes from 'prop-types';
Welcome.propTypes = {
name: PropTypes.string,
};- 🧩 Use Destructuring: Destructure props in the function parameters for cleaner code.
- 🪝 Prop-Drilling: Be aware of prop-drilling; passing props through many layers can make your code harder to maintain.
State is a built-in object that allows components to create and manage their own local state. useState is a React hook that lets you add state to functional components.
- 🗂️ Definition: An object that determines how that component renders & behaves.
- 🏠 Local: Each component can have its own state, independent of other components.
The useState hook is used to declare state variables in functional components.
const [stateVariable, setStateVariable] = useState(initialValue);import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}- 🔄 Functional Updates: When the new state depends on the old state, use the functional form of the state setter.
setCount(prevCount => prevCount + 1);Changing the state with the state setter function causes the component to re-render, reflecting the updated state in the UI.
- 🏁 Initialize State: Always initialize your state variables.
- 🔄 Use Functional Updates: Prefer functional updates when the new state depends on the old state.
Event handling in React is how you manage events triggered by user interactions, like clicks, form submissions, and keyboard input.
- 🧪 React wraps browser events in a synthetic event system to ensure consistency across different browsers.
- 🖱️ Event handlers are passed as props to the components and are usually named using camelCase.
function MyButton() {
function handleClick() {
alert('Button was clicked!');
}
return <button onClick={handleClick}>Click me</button>;
}⚠️ thisKeyword: In class components, you may need to bind thethiskeyword to the event handler to access the component instance.- ➡️ Arrow Functions: Using arrow functions for event handlers automatically binds the correct
thisvalue.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
alert('Button was clicked!');
}
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}To prevent the default behavior of an event (like form submission), use the preventDefault method of the event object.
function MyForm() {
function handleSubmit(event) {
event.preventDefault();
alert('Form submitted!');
}
return <form onSubmit={handleSubmit}>...</form>;
}- ➡️ Use Arrow Functions: Prefer arrow functions for event handlers to avoid binding issues.
- 🧹 Keep Handlers Simple: Keep your event handlers simple and delegate complex logic to other functions.
Conditional rendering in React allows you to render different UI elements or components based on certain conditions, like user authentication status or data availability.
- 🔀 Use JavaScript if-else conditions inside your component to decide what to render.
function Greeting(props) {
if (props.isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <h1>Please sign in.</h1>;
}
}- ⚖️ The ternary operator is a shorthand for if-else and is often used for conditional rendering.
condition ? <TrueComponent /> : <FalseComponent />;function Greeting(props) {
return props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>;
}- ➕ The logical AND operator can be used to conditionally render a component if the condition is true.
function LogoutButton(props) {
return (
<div>
{props.isLoggedIn && <button onClick={props.onLogout}>Logout</button>}
</div>
);
}- 🧹 Keep It Simple: Don’t overuse conditional rendering; keep your components simple and focused.
- ⚖️ Use Ternary for Simple Conditions: Use the ternary operator for simple if-else conditions to keep your code concise.
Rendering lists of data and managing them with keys is a crucial part of building dynamic React applications.
- 📝 You can render lists of elements by mapping over an array and returning a JSX element for each item.
const items = ['Apple', 'Banana', 'Cherry'];
function FruitList() {
return (
<ul>
{items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);
}- 🗝️ Keys are special attributes you need to include when rendering lists of elements. They help React identify which items have changed, are added, or are removed.
- 🆔 Unique: Keys must be unique among siblings.
- 🔒 Stable: Keys should not change between renders.
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}- 🗝️ Always Use Keys in Lists: Forgetting to use keys or using them incorrectly can lead to performance issues and bugs.
- 🆔 Use Unique Identifiers: Use unique and stable identifiers from your data as keys.
Styling in React can be done in various ways, including inline CSS, CSS modules, and styled-components. This section covers the basics of inline CSS and CSS modules.
- 🎨 You can apply styles directly to elements using the
styleattribute. The value is a JavaScript object with camelCased properties.
function MyComponent() {
const divStyle = {
color: 'blue',
backgroundColor: 'lightgray',
padding: '10px',
};
return <div style={divStyle}>Hello, world!</div>;
}- 🗂️ CSS modules are a way to scope your CSS to a specific component, preventing clashes with other styles. Class names are locally scoped by default.
- 📝 Create a CSS Module:
MyComponent.module.css.container { color: blue; background-color: lightgray; padding: 10px; }
- ➕ Import and Use It:
import styles from './MyComponent.module.css'; function MyComponent() { return <div className={styles.container}>Hello, world!</div>; }
- 🗂️ Choose the Right Styling Method: Choose a styling method that fits your project and team preferences.
- 🧩 Keep Styles Organized: Keep your styles organized and modular to avoid conflicts and make maintenance easier.