🧱React Foundations

Build a solid understanding of the core concepts that power React. Perfect for absolute beginners or developers transitioning to React.

πŸ‘‹ Hello, React!

Welcome to the world of React! πŸš€ In this chapter, you'll learn about the fundamentals of React, why it's revolutionizing web development, and how to get started building modern web applications.

πŸ’‘ What is React?

React is a JavaScript library used for building user interfaces. It's maintained by Facebook and the community of individual developers and companies. React allows you to create reusable UI components, making it easier to build complex web applications.

  • React uses a component-based architecture
  • It promotes a unidirectional data flow
  • Uses virtual DOM for efficient updates
  • Supports server-side rendering (SSR)

βœ… Why Use React?

  • Largest ecosystem of UI components available
  • Strong community support and resources
  • High performance with virtual DOM optimizations
  • Adopted by top companies like Facebook, Netflix, Airbnb

πŸ’‘ Single Page Applications (SPAs) vs Multi-Page Applications (MPAs)

React excels at building SPA applications where the entire experience happens on a single page. Here's how they compare:

  • SPAs: Load once, load new content asynchronously
  • MPAs: Reload the page for each request
  • SPAs provide better user experience and SEO with modern techniques

πŸ’‘ Setting Up Your Development Environment

To get started with React, you'll need to set up your development environment. There are two main ways:

  • Using Create React App (CRA) - Quick setup for small projects
  • Using Vite - Modern, fast, and flexible tooling

βœ… Example: Creating a New Project with CRA

$ npx create-react-app my-react-app
$ cd my-react-app
$ npm start

βœ… Example: Creating a New Project with Vite

$ npm create vite@latest my-vite-project --template react
$ cd my-vite-project
$ npm run dev

πŸ’‘ Understanding JSX Syntax

JSX (JavaScript XML) is a syntax extension for React that allows you to write HTML in your JavaScript files. Here are some key points:

  • JSX is converted into regular JavaScript during compilation
  • Must return a single root element or use Fragment
  • Use curly braces {} for embedding JavaScript expressions

βœ… JSX Example

function HelloWorld() {
  return (
    <div>
      <h1>Hello, React!</h1>
      <p>Welcome to the world of React development! πŸš€</p>
    </div>
  );
}

❌ Common Mistakes When Writing JSX

  • Forgetting the closing tag
  • Not using curly braces for JavaScript expressions
  • Writing multiple root elements without a fragment
  • Mixing JSX with regular HTML syntax rules

🧩 Components Demystified

Welcome to Components Demystified! In this chapter, we'll explore the heart of React: components. You'll learn how to build reusable, maintainable UIs by mastering functional and class-based components, understanding props, and composing components effectively.

πŸ’‘ What are Components?

A component is a reusable piece of UI that encapsulates functionality and markup. Think of them as building blocks for your application.

βœ… Functional Components

Functional components are the simplest way to create a component. They take props as input and return JSX output.

function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}

βœ… Class-Based Components

Class-based components extend React.Component and use lifecycle methods. They're useful for managing state and side effects.

class Counter extends React.Component {
  constructor() {
    super();
    this.state = { count: 0 };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
      </div>
    );
  }
}

πŸ’‘ Props: The Lifeblood of Components

Props (short for properties) are the way components communicate. They flow from parent to child and are read-only.

// Parent component
function App() {
  return <Greeting name="React" />;
}

// Child component receives props
function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}

βœ… Component Composition

Composition is the process of combining multiple components into a larger UI. It promotes reusability and modularity.

function App() {
  return (
    <div className="app">
      <Header />
      <MainContent />
      <Footer />
    </div>
  );
}

❌ Avoiding Prop Drilling

Prop drilling happens when props are passed through multiple layers of components. Use React Context or state management libraries to avoid this.

// Bad: Prop drilling
function App() {
  return <Grandchild name="React" />;
}

function Child({ name }) {
  return <Grandchild name={name} />;
}

function Grandchild({ name }) {
  return <p>Hello, {name}</p>;
}

πŸ’‘ Optimizing Component Performance

  • Use React.memo to prevent unnecessary re-renders of functional components.
  • Avoid heavy computations in render methods; use memoization instead.
  • Use efficient state updates with useState's callback syntax.

βœ… Real-World Component Composition

// High-order component pattern
function withLogging(WrappedComponent) {
  return function(props) {
    console.log('Component rendered:', WrappedComponent.name);
    return <WrappedComponent {...props} />;
  };
}

// Render props pattern
functionDataProvider({ children }) {
  const data = useApiCall();
  return children(data);
}

⏳ State and Lifecycle

Welcome to the chapter on State and Lifecycle in React! Understanding state management is crucial for building dynamic and interactive components. We'll explore how to use `useState` and `useEffect` hooks effectively, while also diving into best practices for maintaining clean and efficient code.

πŸ’‘ Understanding State in React

In React, state refers to data that changes over time. Unlike props, which are passed into components and remain static, state allows components to re-render when their underlying data updates.

const [count, setCount] = useState(0);

return (
  <div>
    <p>Count: {count}</p>
    <button onClick={() => setCount(count + 1)}>
      Increment
    </button>
  </div>
)

βœ… Using useState Effectively

The `useState` hook is the primary way to manage state in functional components. Here are some key points to remember:

  • Initialize state with a default value using `useState(initialValue)`.
  • Use the setter function (`setState`) to update state values.
  • State updates are asynchronous but can be chained for sequential updates.

❌ Common Pitfalls with useState

  • Avoid using `useState` unnecessarily - use props or context if possible.
  • Don't directly modify state variables. Always use the setter function.
  • Be cautious with stale closures in callbacks that reference state.

πŸ’‘ Exploring useEffect for Side Effects

The `useEffect` hook allows components to perform side effects such as data fetching, subscriptions, or DOM manipulation. Unlike class lifecycle methods, `useEffect` provides a unified way to manage these operations.

useEffect(() => {
  const fetchData = async () => {
    try {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      setData(data);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  fetchData();

  return () => {
    // Cleanup function to prevent memory leaks
    clearTimeout(timeoutId);
  };
}, [deps]);

βœ… Key Features of useEffect

  • Use the second argument for dependency arrays to control when effects run.
  • Return a cleanup function to handle resources like timers or subscriptions.
  • Chain multiple `useEffect` hooks if needed for separate concerns.

πŸ’‘ Best Practices for State Management

  • Keep state atomic - split complex objects into smaller, more manageable pieces.
  • Use derived data with `useMemo` to optimize performance when working with expensive calculations.
  • Avoid unnecessary re-renders by using functional updates and memoization.
  • Leverage React DevTools to debug state and effects effectively.

πŸ’‘ Advanced State Management Techniques

For more complex applications, consider these advanced patterns:

  • Use `useContext` for state that needs to be shared across multiple components.
  • Implement custom hooks to encapsulate reusable logic.
  • Combine `useState`, `useEffect`, and `useMemo` for optimal performance.

Quiz

Question 1 of 13

What is React primarily used for?

  • Building server-side applications
  • Creating user interfaces
  • Developing mobile apps
  • Designing databases