Tag: React Components

  • Components & State Management in React

    In React, components are the building blocks of the UI, and state management is how data is stored and updated within them. Understanding how components work and how to manage state effectively is essential for building scalable React applications.


    What Are Components?

    A component is a reusable piece of UI that can be independent or composed with other components.

    Types of Components:

    1. Functional Components (Recommended)
    2. Class Components (Legacy)

    ✅ Functional Component (Modern Approach)

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

    ❌ Class Component (Older Approach)

    class Greeting extends React.Component {
      render() {
        return <h1>Hello, {this.props.name}!</h1>;
      }
    }

    React now favors functional components with hooks because they are simpler and more efficient.


    State Management in React

    State is data that changes over time within a component. React re-renders the UI whenever state updates.

    Using useState Hook

    The useState hook allows functional components to store and update state.

    ✅ Example of useState

    import { useState } from "react";
    
    function Counter() {
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>Count: {count}</p>
          <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
      );
    }

    How useState Works:

    • useState(0): Initializes state with 0.
    • setCount(count + 1): Updates state, triggering a re-render.

    Props vs. State

    FeaturePropsState
    DefinitionData passed from parent to childData managed within a component
    MutabilityRead-only (cannot be modified by child)Can be updated with setState (or useState)
    Example<Greeting name="Alice" />const [count, setCount] = useState(0);

    Lifting State Up

    When multiple components need shared state, state is lifted up to the nearest common ancestor.

    ✅ Example of Lifting State

    function ParentComponent() {
      const [value, setValue] = useState("Hello");
      return <ChildComponent value={value} setValue={setValue} />;
    }
    
    function ChildComponent({ value, setValue }) {
      return (
        <div>
          <p>{value}</p>
          <button onClick={() => setValue("Updated!")}>Update</button>
        </div>
      );
    }

    Advanced State Management

    For larger applications, React Context or state management libraries like Redux or Zustand are used.

    Using Context API (Avoid Prop Drilling)

    const ThemeContext = React.createContext("light");
    
    function App() {
      return (
        <ThemeContext.Provider value="dark">
          <ChildComponent />
        </ThemeContext.Provider>
      );
    }
    
    function ChildComponent() {
      const theme = React.useContext(ThemeContext);
      return <p>Current theme: {theme}</p>;
    }

    Summary

    • Components are the fundamental building blocks of React.
    • State is mutable data that causes re-renders when updated.
    • Props pass data between components, but cannot be modified.
    • Lifting state up allows shared state between components.
    • Context API helps manage global state without prop drilling.

    References

    1. React Docs – Components
    2. React Docs – State and Lifecycle
    3. React Docs – Context

  • JSX: JavaScript XML in React

    JSX (JavaScript XML) is a syntax extension for JavaScript used in React. It allows developers to write UI components in a syntax similar to HTML, making code more readable and maintainable. JSX is not required in React, but it’s widely used because it simplifies UI development.


    What is JSX?

    JSX lets you write HTML-like code inside JavaScript. Under the hood, it gets compiled into standard JavaScript function calls.

    Example: JSX vs. JavaScript

    ✅ JSX (Common in React)

    const element = <h1>Hello, world!</h1>;

    ❌ Without JSX (Using React.createElement)

    const element = React.createElement('h1', null, 'Hello, world!');

    JSX makes it easier to structure UI components visually, instead of writing raw JavaScript functions.


    How JSX Works

    JSX is not valid JavaScript—it must be compiled by a tool like Babel before the browser can understand it. Babel transforms JSX into React.createElement() calls.

    For example, this JSX:

    const element = <h1>Hello, world!</h1>;

    Compiles to:

    const element = React.createElement('h1', null, 'Hello, world!');

    This creates a JavaScript object representing the DOM structure, which React uses for efficient updates.


    JSX Rules & Best Practices

    1️⃣ JSX Must Return a Single Parent Element

    return (
      <div>
        <h1>Title</h1>
        <p>Some text</p>
      </div>
    );

    If multiple elements are needed, wrap them inside a <div> or use fragments (<>...</>):

    return (
      <>
        <h1>Title</h1>
        <p>Some text</p>
      </>
    );

    2️⃣ Embedding JavaScript Expressions in JSX

    Use curly braces {} to insert JavaScript inside JSX:

    const name = "Alice";
    const element = <h1>Hello, {name}!</h1>;

    3️⃣ Adding Attributes in JSX

    JSX uses camelCase for attributes instead of HTML-style attributes.

    <img src="image.png" alt="Description" />

    4️⃣ Conditional Rendering in JSX

    Using ternary operators:

    const isLoggedIn = true;
    const message = <h1>{isLoggedIn ? "Welcome back!" : "Please log in"}</h1>;

    Using && (short-circuit evaluation):

    {isLoggedIn && <p>You have new messages</p>}

    JSX vs. HTML: Key Differences


    Summary

    • JSX lets you write UI code in a familiar, HTML-like syntax within JavaScript.
    • It compiles to React.createElement() calls for React to process efficiently.
    • JSX requires a single parent element and follows JavaScript syntax rules.
    • You can embed JavaScript expressions and conditionally render elements using JSX.

    References

    1. React Docs – JSX
    2. Understanding JSX in React
    3. Babel JSX Compiler