Top React Interview Questions and Answers

Get ready for your React interview. Find explanations for frequently asked React concepts, best practices, and potential interview topics.

Top-React-Interview-Questions-and-Answers
Table of Contents

What is React?

React is a popular JavaScript library designed for building interactive user interfaces. Unlike traditional libraries, React breaks down complex UIs into smaller, self-contained building blocks called components. Each component encapsulates its functionality and appearance, making your code easier to understand and manage.

Example

import React from 'react';

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

export default Greeting;

Explanation

  • Line 1: Imports the React library to enable JSX syntax and React functionality.
  • Line 3: Declares a functional component named Greeting that takes name as a prop. This allows the component to receive a name value when it is used.
    • Line 4-6: Returns a single <h1> element that displays a greeting message incorporating the name prop. The curly braces { } are used to embed the name prop value within the JSX.
  • Line 9: Exports the Greeting component to be imported and used in other application parts.

The beauty of React lies in its ability to combine and nest these components to create intricate UIs. Components can also receive data from parent components (props) and manage their internal state (data specific to the component). This flexibility and modularity make React a powerful tool for building modern web applications that adapt and respond to user interactions.

React InShort

  • JavaScript Library: React is a popular JavaScript library used for building user interfaces (UIs).
  • Focus on Components: React is all about creating reusable UI components at its core. Think of them as building blocks that you put together to create web applications.
  • Declarative Approach: You describe the desired UI, and React efficiently updates the actual DOM (the browser’s representation of a webpage) to match your specifications. This makes development faster and code easier to reason about.
  • Not a Framework: React focuses primarily on web applications’ view layer (the UI part). It often works alongside other libraries and tools for a complete application solution.

Why use React?

Traditional web development, especially with large and complex UIs, can become cumbersome to manage. Here’s where React shines. It tackles several challenges by

  • Component-Based Architecture: Promotes reusability and code organization. Build complex interfaces from smaller, manageable components.
  • Virtual DOM and Performance: Provides efficient updates, leading to a smoother and more responsive user experience.
  • Declarative Style: Focus on describing the desired UI, making code easier to read and maintain.
  • Large Ecosystem and Community: Access extensive support, resources, and a vast developer community.
  • Cross-Platform Development: Use React Native to build native mobile apps, sharing code and knowledge between web and mobile projects.

Example of Simple Counter Component in React

import React, { useState } from 'react'; // Import useState hook

function Counter() {
    const [count, setCount] = useState(0); // Initialize state with useState

    function handleClick() {
        setCount(count + 1); // Update state using setCount
    }

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={handleClick}>Click me</button>
        </div>
    );
}

export default Counter;

Explanation

  • Line 1: Imports React and the useState hook for state management.
  • Lines 3-4: Defines a functional component named Counter.
    • Line 4: Initializes state using useState: count stores the click count (initially 0) and setCount is used to update it.
  • Lines 6-8: Define a handleClick function to increment the count.
    • Line 7: Updates the count state using setCount.
  • Lines 10-15: JSX structure displays the count and a button trigger.
  • Line 13: The button calls handleClick on click, updating the state (count).
  • Lines 18: Exports the component for reusability.

In this example, the state (count) and the function to update it (setCount) are encapsulated within the Counter component, promoting efficient management of dynamic UI updates.


How to create a new React project?

Getting started with React is a breeze! Here’s a step-by-step guide to creating a fresh React project:

Prerequisites

Node.js and npm: React development relies on Node.js, a JavaScript runtime environment, and npm (Node Package Manager) for managing JavaScript packages. Download and install Node.js from the official website (https://nodejs.org/) as it typically includes npm.

1. Install Create React App (CRA)

The recommended approach is to use Create React App (CRA), a tool that streamlines setting up a new React project with all the essential configurations pre-configured. To install CRA globally on your machine, open your terminal or command prompt and run the following command:

npm install -g create-react-app

Explanation

  • npm: The Node Package Manager, used to install JavaScript packages.
  • install: The command to install a package.
  • -g: Flag for global installation, making create-react-app accessible anywhere on your system.
  • create-react-app: The name of the package we’re installing.

2. Create a New Project

Once CRA is installed, navigate to your desired project directory in your terminal and run the following command, replacing my-react-app with your preferred project name:

npx create-react-app my-react-app

Explanation

  • npx: Executes a package from npm without global installation.
  • create-react-app: The name of the command to be executed.
  • my-react-app: The name you’re giving to your new React project.

3. Project Structure

CRA creates a well-organized project structure with all the necessary files and folders for your React application. You can start coding within the src directory, which houses the core components and functionalities of your project.

4. Running the Development Server

To launch your React application in a development environment for testing and live coding, navigate to your project directory in the terminal and run:

npm start

Explanation

  • npm: The Node Package Manager.
  • start: Initiates the development server as defined in the project’s scripts (usually found in package.json).

This will typically open your default web browser and display your React application at http://localhost:3000/ by default (the port might vary).


What is JSX?

JSX (JavaScript Syntax Extension) plays an important role in React development. It’s a syntactic sugar that allows you to write HTML-like structures directly within your JavaScript code. This bridges the gap between UI definition and logic, making it easier to visualize and manage the appearance of your React components.

Example of JSX

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

Explanation

  • Line 1: Defines a function named Hello that represents a React component.
  • Line 2: The return statement specifies what the component will render on the screen.
  • Line 3: Returns a div element, a container element in HTML.
  • Line 4: Nestled within the div, an h1 element displays the text “Hello, World!”.
  • Line 5: Closing div tag.
  • Line 6: Closing parenthesis for the return statement.
  • Line 7: Closing curly brace for the component definition.

Key Points about JSX

  • JSX elements resemble HTML elements but are written within curly braces { }.
  • It doesn’t directly translate to HTML; React processes JSX and transforms it into regular JavaScript function calls.
  • JSX improves readability and maintainability of React components by keeping UI structure and logic in the same place.

React Components: What Are They and How Do I Create Them?

React applications are built upon reusable components, the fundamental units that structure and control your web page’s appearance and behavior. Each component acts like a self-contained module responsible for its UI and logic. This modular approach promotes code organization, maintainability, and reusability.

Example of Basic React Component

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

Explanation

  • Line 1: Defines a function named Greeting that accepts a parameter named name. This parameter will be used to personalize the greeting message.
  • Line 2: The return statement defines the UI content the component will render.
  • Line 3: Returns an h1 element displaying the text “Hello, “ followed by the value of the name parameter enclosed in curly braces { }. This demonstrates how React utilizes JSX syntax to write HTML-like structures within JavaScript.
  • Line 4: Closing parenthesis for the return statement.
  • Line 5: Closing curly brace for the component definition.

Key Points about React Components

  • Components are reusable. You can use the same component throughout your application with different props (data passed to the component).
  • Each component controls its state, allowing components to manage their internal data and update the UI accordingly.
  • Components can be nested – you can build complex UIs by combining simpler components.

Differences between class components and functional components in React.

React offers two primary approaches to creating components: class components and functional components. While both serve the purpose of building UI elements, they differ in syntax and functionality.

Class Components

Class components leverage the concept of classes from JavaScript, allowing you to define state and lifecycle methods within the component’s class definition.

class Message extends React.Component {
    constructor(props) {
        super(props);
        this.state = { message: "Hello!" };
    }

    render() {
        return (
            <div>
                <h1>{this.state.message}</h1>
            </div>
        );
    }
}

Explanation

  • Line 1: Defines a class named Message that inherits from React.Component.
  • Line 2: The constructor is a special method invoked when a class component is created. It’s used to initialize state.
  • Line 3: Calls the parent class (React.Component) constructor using super().
  • Line 4: Defines the component’s initial state using this.state. In this case, the state holds a property named message with the value “Hello!”.
  • Line 7: Defines the render method, a lifecycle method responsible for returning the UI content the component will display.
  • Line 8: The return statement specifies the JSX for the component’s UI.
  • Line 9-12: Renders a div containing an h1 element that displays the value of the message state property using this.state.message.
  • Line 13: Closing parenthesis for the return statement.
  • Line 14: Closing curly brace for the class definition.

Functional Components

Functional components, introduced in React 16.8, are simpler and more concise. They are pure JavaScript functions that accept props (data passed to the component) and return JSX to define the UI.

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

Explanation

  • Line 1: Defines a function named Greeting that accepts a single parameter named props.
  • Line 2: The return statement specifies the JSX for the component’s UI.
  • Line 3: Returns an h1 element displaying the text “Hello, “ followed by the value of the name prop using props.name.
  • Line 4: Closing parenthesis for the return statement.
  • Line 5: Closing curly brace for the function definition.

Key Differences

  • State Management: Class components can manage internal state using this.state, while functional components rely on props for data and cannot have their state.
  • Lifecycle Methods: Class components can access lifecycle methods like componentDidMount and componentDidUpdate for handling side effects and updates based on the component’s lifecycle. Functional components don’t have built-in lifecycle methods but can leverage hooks (introduced in React 16.8) to achieve similar functionality.
  • Syntax: Class components use a class-based syntax with a constructor and methods, while functional components are simply JavaScript functions.

What are props in React?

React components are designed to be modular and reusable. To customize the behavior and appearance of a component when used in different contexts, React utilizes props (short for properties). Props act as a way to pass data down from parent components to their child components.

Example of How Props Work in React

function Greeting(name) { // Notice the parameter 'name'
    return (
        <h1>Hello, {name}!</h1>
    );
}
function App() {
    const recipient = "World"; // Data to be passed as a prop
    return (
        <div>
            <Greeting name={recipient} />  {/* Passing 'recipient' as a prop */}
        </div>
    );
}

Explanation

  • Line 1: Defines a function named Greeting that accepts a parameter named name. This parameter serves as a prop to customize the greeting message.
  • Line 2-4: The Greeting component’s logic remains the same.
  • Line 6: Defines a new function named App that represents the parent component.
  • Line 7: Creates a variable named recipient that holds the data (“World”) you want to pass to the Greeting component.
  • Line 8: The return statement defines the UI content for the App component.
  • Line 9: Renders a div element.
  • Line 10: Within the div, the Greeting component is used. Notice the name prop set to the recipient variable using curly braces { }. This is how data is passed from the parent (App) to the child (Greeting) component.
  • Line 11: Closing div tag.
  • Line 12-13: Closing parenthesis and curly brace for the App component definition.

Key Points about Props

  • Props are read-only within the receiving component – the child component cannot modify them.
  • Props allow for flexible component usage. You can reuse the same component with different data by passing various values through props.
  • Data flows unidirectionally in React. Parent components pass data down to child components, promoting better organization and predictability.

What is state in React?

In React, components can maintain their internal state to dynamically control their behavior and appearance. This state represents data specific to the component that can change over time, triggering the component to re-render with the updated information.

Example of State in React

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

    handleClick = () => {
        this.setState({ count: this.state.count + 1 });
    }

    render() {
        return (
            <div>
                <h1>Count: {this.state.count}</h1>
                <button onClick={this.handleClick}>Increment</button>
            </div>
        );
    }
}

Explanation

  • Line 1: Defines a class component named Counter.
  • Line 2-4: The constructor initializes the component’s state. Here, the state object holds a single property named count with an initial value of 0.
  • Line 6: An empty line for better readability.
  • Line 7: Defines a method named handleClick. This method will be called when the button is clicked.
  • Line 8: Uses this.setState to update the component’s state. The new state is defined as an object with the count property incremented by 1.
  • Line 11: Defines the render method responsible for UI rendering.
  • Line 12-17: Renders a div containing an h1 element that displays the current value of the count state property using this.state.count. It also renders a button with an onClick event handler set to the handleClick method.
  • Line 18: Closing parenthesis for the render method.
  • Line 19: Closing curly brace for the class definition.

Key Points about State

  • State is internal to a component – not directly accessible by other components.
  • State updates trigger re-renders – whenever the state changes using this.setState, the component will re-render its UI with the updated information.
  • State can be managed using class components or functional components with hooks (introduced in React 16.8).

How do I update state in a React component?

React components can hold internal state to manage dynamic behavior and UI updates. But how do you modify this state? Here’s where the setState method comes into play.

Updating State with setState

The setState method is a built-in function used within React components to update their state. It allows you to schedule changes to the component’s state, triggering a re-render with the updated information reflected in the UI.

Example of State Updates

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

    handleClick = () => {
        // Update state using setState
        this.setState({ count: this.state.count + 1 });
    }

    render() {
        return (
            <div>
                <h1>Count: {this.state.count}</h1>
                <button onClick={this.handleClick}>Increment</button>
            </div>
        );
    }
}

Explanation

  • Line 1-4: Defines a class component named Counter. The constructor initializes the state with a count property set to 0.
  • Line 6: An empty line for better readability.
  • Line 7: Defines a method named handleClick that will be called when the button is clicked.
  • Line 8: This line is crucial – it uses this.setState to update the component’s state.
  • Line 9: Inside setState, we define an object with the updated state. Here, the count property is incremented by 1.
  • Line 11: Another empty line for readability.
  • Line 12-17: The render method displays the current count and an increment button with an onClick handler set to handleClick.
  • Line 18-20: Closing parenthesis and curly braces for the render method and class definition.

Key Points about Updating State

  • Never modify state directly – always use setState to schedule updates.
  • setState may be asynchronous – React batches state updates for performance reasons. Please don’t rely on the previous state value directly within setState, as it might not reflect the latest state yet. If you need to access the previous state, use a function form of setState that receives the previous state as an argument.

State updates trigger re-renders – whenever you call setState, React will re-render the component and its children with the updated state.


How does React handle user events (like button clicks)?

React applications are naturally interactive, allowing users to engage with UI elements like buttons, forms, and more. To handle these user interactions, React employs an event-driven approach.

Event Handlers and JSX

React components can define event handlers as functions within the component’s code. These handlers are then attached to specific HTML elements using JSX syntax. When the user triggers the event (e.g., clicks a button), the corresponding event handler function is executed.

Example of Event Handling in React

function Greeting(props) {
    const handleClick = () => {
        alert("Button Clicked!");
    }

    return (
        <div>
            <button onClick={handleClick}>Click Me</button>
        </div>
    );
}

Explanation

  • Line 1: Defines a functional component named Greeting.
  • Line 2: Defines a function named handleClick that will be called when the button is clicked. This function displays an alert message.
  • Line 4: Closing curly brace for the handleClick function definition.
  • Line 6: The return statement defines the UI content for the component.
  • Line 7: Renders a div element.
  • Line 8: Within the div, a button element is rendered. The crucial part is the onClick attribute set to the handleClick function. This establishes the connection between the button click event and the function that handles it.
  • Line 9: Closing div tag.
  • Line 10-11: Closing parenthesis and curly brace for the component definition.

Key Points about Event Handling

  • Event handlers are JavaScript functions – they define the logic to be executed in response to a user interaction.
  • The onClick attribute is commonly used for button clicks, but React supports various event types (e.g., onChange for form input changes and onMouseOver for hover events).
  • Event handlers receive an event object as an argument (optional) containing details about the event.

What are the key files in a React project?

A well-organized React project adheres to a specific structure that houses essential files and folders for development. Here’s a breakdown of some key files you’ll encounter:

1. package.json

This file is the heart of your project, managing dependencies (external libraries your project relies on) and configurations like scripts for starting the development server or building your production application.

2. public folder

This folder contains static assets that are directly accessible by the browser, such as favicons, images, or any public HTML files needed for your application.

3. src folder

This folder serves as the core of your React application, encompassing all your source code. Here are some significant files within src:

  • index.js: This is the entry point for your React application. It typically renders the root component of your application and ties everything together.

Example Code (src/index.js)

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App'; // Assuming your root component is named App.js
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);

Explanation

  • Line 1: Imports the React library, essential for building React components.
  • Line 2: Imports ReactDOM from react-dom/client (assuming you’re using React 18 or later). This is used to render React components in the browser.
  • Line 3: Imports your main application component, typically named App.js.
  • Line 4: Creates a root element using ReactDOM.createRoot where your React application will be rendered.
  • Line 5-9: Renders the App component within the root element wrapped in React.StrictMode (optional for development to highlight potential issues).
  • App.js (or your root component): This file houses your root component, the top-level component that defines your application’s overall structure. It usually renders child components and manages application state (if needed).
  • Other component files (e.g., Header.js, Footer.js, etc.): These files define reusable components that make up the building blocks of your UI. Each component typically manages its state and logic.

4. Additional Files

Depending on your project’s needs, you might encounter other files like:

  • index.html (in the root directory): This base HTML file typically references the React application’s entry point (src/index.js).
  • .gitignore (optional): This file specifies files or folders that should be excluded from version control using Git.

How do I pass data between components in React?

React applications are often composed of multiple components working together. To enable communication and data exchange between these components, React utilizes props (short for properties).

Props: A One-Way Street

Props act as a mechanism for parent components to pass data down to their child components. This data flow is unidirectional – child components cannot directly modify the props they receive. Here’s a glimpse of how props work:

Example

function Profile(props) { // Child component
    return (
        <div>
            <h1>Hello, {props.name}!</h1>
            <p>Age: {props.age}</p>
        </div>
    );
}
function App() { // Parent component
    const userName = "Alice";
    const userAge = 30;
    return (
        <div>
            <Profile name={userName} age={userAge} /> {/* Passing props */}
        </div>
    );
}

Explanation

  • Line 1: Defines a functional component named Profile that accepts props as an argument.
  • Line 2-7: The Profile component displays a heading and paragraph using the name and age props received through curly braces { }.
  • Line 9: Defines a functional component named App representing the parent component.
  • Line 10-11: Creates variables userName and userAge to hold the data to be passed.
  • Line 12-16: The App component returns JSX. Notice the Profile component is used within the div. Here’s the key part: name={userName} and age={userAge} are prop assignments. These expressions define the values passed to the child component (Profile) as props.
  • Line 14: Closing tag for the Profile component usage.

Key Points about Props

  • Props are read-only within the receiving component – the child component cannot modify them.
  • Props allow for flexible component usage. You can reuse the same component with different data by passing various values through props.
  • Data flows unidirectionally in React. Parent components pass data down to child components, promoting better organization and predictability.

How to make API calls / fetch data in React?

React applications often interact with external APIs to retrieve data and populate the UI dynamically. Here’s a breakdown of how to make API calls in React:

Fetch API or Third-Party Libraries

React itself doesn’t directly handle API calls. You can leverage the built-in Fetch API or popular libraries like Axios for making HTTP requests.

Example (Using Fetch API)

import React, { useState, useEffect } from 'react';

function PostsList() {
    const [posts, setPosts] = useState([]);
    useEffect(() => {
        fetch('https://api.example.com/posts')
            .then(response => response.json())
            .then(data => setPosts(data))
            .catch(error => console.error(error));
    }, []);

    return (
        <div>
            <h1>Posts</h1>
            {posts.map(post => (
                <div key={post.id}>
                    <h2>{post.title}</h2>
                    <p>{post.content}</p>
                </div>
            ))}
        </div>
    );
}

export default PostsList;

Explanation

  • Line 1: Imports the necessary hooks (useState and useEffect) from the React library, along with React itself.
  • Line 3-23: Defines a functional component named PostsList.
    • Line 4: Initializes a state variable posts with an empty array. This state will store the posts fetched from the API.
    • Line 5-10: Uses the useEffect hook to fetch posts from an API when the component mounts. The empty array [] as the second argument means this effect runs only once after the initial render.
      • Line 6-9: Fetches data from the provided URL, converts the response to JSON, updates the posts state with the fetched data, and catches any errors.
    • Line 12-21: Returns JSX that displays a list of posts. Each post is wrapped in a <div> with a unique key prop using post.id, and displays the post’s title and content.
  • Line 25: Exports the PostsList component so it can be used in other parts of the application.

Key Points about Fetching Data

  • The Fetch API provides a basic mechanism for making HTTP requests.
  • Libraries like Axios offer a more user-friendly experience for handling API calls.
  • State management is crucial for storing and displaying fetched data in React components.
  • Error handling is essential to handle potential issues during API requests gracefully.

How to style React components?

React offers various approaches to style your components, allowing you to define the visual appearance of your UI elements. Here’s an overview of some popular methods:

1. Inline Styles

Inline styles involve attaching CSS styles directly to JSX elements using the style attribute as an object.

Example

function Button(props) {
    const buttonStyle = {
        backgroundColor: 'blue',
        color: 'white',
        padding: '10px 20px',
    };

    return (
        <button style={buttonStyle}>
            {props.text}
        </button>
    );
}

Explanation

  • Line 1: Defines a functional component named Button that accepts a prop named text.
  • Line 2-6: Creates a JavaScript object named buttonStyle containing CSS properties for styling the button.
  • Line 8-12: The return statement defines the JSX for the button.
  • Line 9: Renders a button element.
  • Line 9: The style attribute is set to the buttonStyle object, applying the defined styles inline.
  • Line 10: Displays the button text using the props.text.

2. CSS Modules

CSS Modules provide a way to scope CSS styles to specific components, preventing naming conflicts between components. A unique class name is generated for each CSS class defined within a module file.

Example (CSS Module)

styles.module.css

.button {
  background-color: blue;
  color: white;
  padding: 10px 20px;
}

Button.js

import styles from './styles.module.css'; // Import the CSS module
function Button(props) {
    return (
        <button className={styles.button}>
            {props.text}
        </button>
    );
}

Explanation

  • styles.module.css: This file defines the CSS styles for the button. Due to the module format, the class name .button is automatically scoped to this component.
  • Line 1 (Button.js): Imports the CSS module named styles from the corresponding file (styles.module.css).
  • Line 2-7: Similar to the inline style example, the Button component defines the button element.
  • Line 4: The className attribute is set to styles.button, referencing the class name from the CSS module.

3. CSS-in-JS Libraries

Third-party libraries like styled-components allow you to write CSS styles directly within JavaScript using template literals. This approach promotes better organization and maintainability of styles alongside your components.


Can I use my existing CSS with React?

Yes, You Can! Integrating Existing CSS with React

While React offers various styling methods like CSS Modules and CSS-in-JS libraries, you can leverage your existing CSS styles with your React components. Here’s how:

Including External Stylesheets

The simplest approach is to link your existing CSS file to your React application’s main HTML file.

Example (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My React App</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <script src="index.js"></script>
</body>
</html>

Explanation

  • Line 7: Notice the <link> tag within the <head> section.
  • Line 8: The rel attribute is set to “stylesheet” to specify an external stylesheet.
  • Line 8: The href attribute points to the path of your existing CSS file (styles.css in this case).

Considerations

  • When using existing CSS with React, ensure a well-organized and well-structured CSS codebase to avoid potential style conflicts.
  • Using methodologies like BEM (Block-Element-Modifier) can help improve the specificity of your CSS selectors and minimize conflicts within React components.

Simple React Project Examples for Beginners

Learning React often involves hands-on experience. Here are some beginner-friendly project ideas to kickstart your React development journey:

To-Do List Application

This classic example helps you grasp component creation, state management, and user interaction. Users can add, remove, and mark to-do items as complete.

Example (App.js)

import React, { useState } from 'react';
function App() {
    const [todos, setTodos] = useState([]); // State to hold to-do items
    const addTodo = (text) => {
        setTodos([...todos, { text, completed: false }]);
    };
    const removeTodo = (index) => {
        const newTodos = [...todos];
        newTodos.splice(index, 1);
        setTodos(newTodos);
    };
    const toggleTodo = (index) => {
        const newTodos = [...todos];
        newTodos[index].completed = !newTodos[index].completed;
        setTodos(newTodos);
    };
    return (
        <div className="App">
            <h1>To-Do List</h1>
            <input type="text" placeholder="Add a to-do..." onChange={(e) => addTodo(e.target.value)} />
            {todos.map((todo, index) => (
                <div key={index}>
                    <input type="checkbox" checked={todo.completed} onChange={() => toggleTodo(index)} />
                    <span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>{todo.text}</span>
                    <button onClick={() => removeTodo(index)}>Remove</button>
                </div>
            ))}
        </div>
    );
}
export default App;

Explanation

  • Line 1: Imports useState from React for managing state within the component.
  • Line 3: Defines a state variable todos (using useState) to store an array of to-do items, initially empty.
  • Line 4-6: The addTodo function takes user input text and adds a new to-do object to the todos state array with properties for text and completion status.
  • Line 7-11: The removeTodo function removes a to-do item at a specific index from the todos state array using spread syntax (...todos) and splice.
  • Line 12-16: The toggleTodo function toggles the completion status of a to-do item based on its index in the todos state array.
  • Line 17-29: The return statement defines the application’s UI using JSX.
  • Line 19: Displays a heading “To-Do List”.
  • Line 20: Creates an input field for adding new to-do items. The onChange event handler calls addTodo with the user input value.
  • Line 21-27: The todos array is mapped to create individual to-do items.
  • Line 23: A checkbox marks to-do items as complete, calling toggleTodo on change.
  • Line 24: The to-do text displays conditional styling for completed items (line-through decoration).
  • Line 25: A button for removing to-do items calls removeTodo with the current index.

This example showcases fundamental React concepts like state management, user input handling, and conditional rendering, making it a great starting point for beginners.


Best resources for learning React for beginners.

Here are some excellent resources for beginners to embark on their React learning journey:

Official Resources

  • React Documentation (https://react.dev/): Provides the most comprehensive and reliable source of information directly from the React team. The tutorials and guides offer a well-structured introduction to core concepts.

Online Courses and Tutorials

Interactive Platforms

  • Codecademy (https://www.codecademy.com/): Provides interactive lessons and tutorials for learning React in a structured environment.
  • CodeSandbox (https://codesandbox.io/): An online environment for quickly creating and experimenting with React projects directly in your web browser.

Additional Tips

  • Focus on Projects: The best way to learn React is to build things. Start with small projects and gradually increase complexity as you gain confidence.
  • Communities: Engage with React communities on forums like Reddit (r/reactjs), Stack Overflow, or Discord servers to ask questions and get help from other developers.