DEV Community

A Ramesh
A Ramesh

Posted on

What I Learned Today in React: useState, Spread Operator & Map Function...

Today, I made good progress in learning React by exploring some very important concepts: useState, the spread operator (...), and the map() function. These features are essential for building dynamic and interactive components in React. Below, I’ll share what I learned with simple explanations and examples.


1. useState Hook – Managing State in Functional Components

In React, state is used to store data that can change over time. The useState hook helps us add state to functional components.

Syntax:

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode

Example:

import React, { useState } from 'react';

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

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, clicking the button increases the count by 1 using the setCount function.


2. Spread Operator (...) – Copying and Updating Arrays/Objects

The spread operator helps us create copies of arrays or objects and add new values without changing the original.

Array Example:

const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4];  // Output: [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Object Example:

const user = { name: 'Ramesh', age: 25 };
const updatedUser = { ...user, age: 26 };  // Output: { name: 'Ramesh', age: 26 }
Enter fullscreen mode Exit fullscreen mode

This method is useful in React when updating state without directly modifying the existing data.


3. map() Function – Rendering Lists in React

React allows us to display lists of items dynamically using the JavaScript map() function.

Example:

const fruits = ['Apple', 'Banana', 'Orange'];

function FruitList() {
  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{fruit}</li>
      ))}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

The map() function loops through each item in the fruits array and displays it inside a list item (<li>). The key is used to uniquely identify each element.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.