Core Concepts

Functional components and props

Functional components are the most common and modern way to build UI in React. They are simple JavaScript functions that return JSX and describe what the UI should look like. Props, short for “properties,” allow data to be passed from a parent component to a child component, making components dynamic and reusable.

What are Functional Components?

Functional components are plain JavaScript functions that return React elements (JSX). Unlike class components, they do not have their own state or lifecycle methods (although they can manage state using React hooks like useState and useEffect).

Syntax Example:

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

Or with an arrow function:

const Greeting = () => <h1>Hello, World!</h1>;

What are Props?

Props are inputs to components. They allow you to pass data and event handlers from one component to another, typically from a parent to a child. Props are read-only and cannot be modified by the receiving component.

How to Pass Props:

You pass props to a component like HTML attributes:

<Greeting name=”Alice” />

Accessing Props in Functional Components:

Props are received as a function argument:

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

Or with destructuring:

const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;

Why Use Props?

  • To make components reusable with different inputs
  • To separate logic and presentation
  • To create a unidirectional data flow (top-down)

Example: Parent to Child Component Communication

function App() {
return <Greeting name=”Alice” />;
}

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

This structure makes your components clean, modular, and easier to maintain. It’s also fundamental to React’s design philosophy of building composable UIs with a clear data flow.

State and lifecycle basics

State and Lifecycle Basics in React

Understanding state and lifecycle is essential for building interactive and dynamic React applications. While props allow you to pass data into components, state allows a component to manage and respond to internal changes. Lifecycle refers to the phases a component goes through during its existence—mounting, updating, and unmounting.

What is State in React?

State is a built-in React object used to store dynamic data in a component. It is local to the component and can change over time, usually in response to user actions or other events.

Using useState Hook (Functional Components):

The Usestate hook allows functional components to manage state.

Example:

import { 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>
);
}

  • Usestate is the current state value.
  • Setcount is the function used to update the state.
  • The state update causes the component to re-render with the new value.

Rules of Using State:

  • You must call Usestate at the top level of the component.
  • You can have multiple Usestate calls for different state variables.
  • State updates are asynchronous and batched for performance.

What is Lifecycle in React?

The lifecycle of a component defines how it is created, updated, and destroyed. In functional components, lifecycle behaviors are managed using hooks like useEffect.

Component Lifecycle Phases:

  • Mounting: When the component is first rendered into the DOM.
  • Updating: When state or props change, and the component re-renders.
  • Unmounting: When the component is removed from the DOM.

UseEffect Hook: Replacing Lifecycle Methods

TheUseeffect hook lets you perform side effects (like fetching data, setting up timers, etc.) in functional components.

Example:

import { useState, useEffect } from ‘react’;

function Timer() {
const [seconds, setSeconds] = useState(0);

useEffect(() => {
const interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);

// Cleanup function (runs on unmount)
return () => clearInterval(interval);
}, []); // Empty dependency array means run once (on mount)

return <p>Timer: {seconds} seconds</p>;
}

  • The effect runs once after the first render (like Componentdidmount).
  • The cleanup function is called when the component unmounts (like Componentwillunmount).
  • You can re-run the effect on updates by adding dependencies in the array.

Why State and Lifecycle Matter:

  • State lets components react to user input and events.
  • Lifecycle logic ensures side effects like API calls or subscriptions are properly handled.
  • Together, they enable building interactive and responsive UI elements like forms, modals, sliders, timers, and more.

Best Practices:

  • Keep state minimal and only store what’s necessary.
  • Use separate state variables for unrelated data.
  • Always clean up subscriptions or timers in Useeffect to prevent memory leaks.

This combination of state and lifecycle hooks makes functional components as powerful as class components, but with cleaner and more concise code.

Event Handling in React

Event handling in React is how components respond to user interactions like clicks, typing, hovering, and form submissions. React uses a system called synthetic events, which wraps around the browser’s native events to provide a consistent interface across different browsers.

Synthetic Events

React’s synthetic event system ensures that events behave the same way in every browser. It wraps native DOM events with additional features for compatibility and performance. When a user interacts with an element, React creates a synthetic event object that contains all standard event properties and methods.

Naming and Syntax

React uses camelCase naming for event handlers. For example, a click event is named onClick, not onclick as in regular HTML. Instead of strings, React expects functions to be passed as handlers. This means you write JavaScript functions and reference them directly in your component.

Creating and Using Handlers

Handlers are typically defined inside your component. They can perform tasks like updating state, calling APIs, or logging messages. The function you write receives the event object as its first argument, allowing access to details like which key was pressed or which element was clicked.

Passing Data to Handlers

Sometimes you want to pass custom data along with the event. In React, this is commonly done using inline arrow functions, which give you access to both the event and additional parameters.

Preventing Default Behavior

Forms and links often have default browser behaviors. To stop them, use the event object’s method that cancels the default action. For example, stopping a form from reloading the page when submitted.

Stopping Event Propagation

If you want to stop an event from bubbling up to parent elements, React supports a method that allows you to prevent the event from continuing its journey up the component tree. This is useful for isolating interaction within specific parts of the UI.

Common Event Types

  • Click events handle user clicks on buttons or links.
  • Change events track input value changes in forms.
  • Submit events process form data when submitted.
  • Keyboard events capture key presses and releases.
  • Mouse events track actions like hovering or moving the cursor.

Best Practices

  • Use meaningful names like handleClick or handleSubmit to keep code readable.
  • Define handler functions separately instead of inline when possible to improve performance.
  • Use functional updates to ensure correct state changes when relying on previous values.
  • Keep side effects, such as logging or external calls, within controlled event flows.

Understanding and applying React’s event system correctly allows developers to build responsive, accessible, and user-friendly interfaces with predictable behavior.

Conditional rendering

Conditional Rendering in React

Conditional rendering in React refers to the process of showing or hiding elements in the UI based on certain conditions. It allows components to render different content or components depending on the state, props, or logic within the application.

Why Use Conditional Rendering

It helps in creating dynamic and responsive user interfaces. Depending on user interactions, data loading status, authentication states, or feature flags, you can control what content is displayed to the user.

Common Use Cases

  • Displaying different views based on user login status
  • Showing loading indicators while data is being fetched
  • Rendering error messages when something goes wrong
  • Conditionally showing or hiding form elements or buttons

Techniques for Conditional Rendering

React supports multiple ways to conditionally render elements. You can use JavaScript expressions, ternary operators, logical operators, or return statements based on conditions.

Using If-Else Logic

Inside a function component, you can use standard if-else conditions to decide what JSX to return based on some logic or values.

Using Ternary Operators

A compact way to render one of two possible elements based on a condition. This is useful for simple true/false checks and inline rendering.

Using Logical AND Operator

This method allows rendering an element only if a condition is true. If the condition is false, nothing is rendered. It’s useful for optional elements like alerts or status messages.

Using Switch Statements

For multiple condition checks, a switch-case structure can be used to render different elements based on the value of a variable. This helps keep code organized when there are several possible UI outcomes.

Returning Null

If you want to conditionally hide a component, you can return null instead of JSX. This tells React to render nothing and skip that part of the UI.

Best Practices

  • Keep logic simple and readable
  • Extract complex conditions into variables for clarity
  • Avoid deeply nested ternary operators for maintainability
  • Use descriptive variable and function names

Mastering conditional rendering in React allows you to create flexible, responsive interfaces that adapt to user input and application state with ease.

Rendering lists with keys

Rendering Lists with Keys in React

Rendering lists in React is a common task when displaying arrays of data, such as items in a menu, products in a catalog, or users in a table. React allows you to map over arrays and create dynamic sets of elements based on data.

Why Use Keys

Keys are special string attributes that help React identify which items have changed, been added, or removed. They improve performance and help React manage and update the DOM efficiently during re-rendering.

How Lists Are Rendered

React components often use array methods like map to loop through data and return an array of elements. Each element in the list needs a unique key so React can track and optimize its updates.

Choosing the Right Key

The best key is a stable, unique identifier that doesn’t change over time. This is often an ID from your data source. Avoid using array indexes as keys unless there is no other unique identifier, especially in dynamic lists where order may change.

Impact of Missing or Incorrect Keys

If keys are not provided or are reused incorrectly, React may re-render or rearrange components inefficiently, leading to unexpected behavior and performance issues.

Best Practices

  • Use a unique and consistent key for each item in the list
  • Avoid using array indexes as keys if items are added, removed, or reordered
  • Extract list items into components when they become complex
  • Keep the map logic clean and readable

Properly rendering lists with keys ensures React can optimize rendering, leading to better performance and more predictable UI behavior.

Leave a Comment