DEV Community

Chithra Priya
Chithra Priya

Posted on

I Learned today - Hooks concept Arrays, Spread Operator, map(), in React...

What is a Hook?

Hooks allow function components to have access to state and other React features. Because of this, class components are generally no longer needed.

Hooks allow us to "hook" into React features such as state and lifecycle methods.

Why used Hooks?

Although Hooks generally replace class components, there are no plans to remove classes from React.

Hook Rules**

There are 3 rules for hooks:

Hooks can only be called inside React function components.
Hooks can only be called at the top level of a component.
Hooks cannot be conditional

Note: Hooks will not work in React class components.

useState in React

React's useState hook lets you add state to functional components.
Basic usage:

import { useState } from 'react';

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

return (


Count: {count}


setCount(count + 1)}>Increase

);
}

Arrays in JavaScript

An array is a list-like object used to store multiple values in a single variable.

const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // Output: apple

Arrays can hold any data type โ€” strings, numbers, objects, or even other arrays.

The Spread Operator (...)

The spread operator allows you to quickly copy or merge arrays and objects.
Copying an array:

const original = [1, 2, 3];
const copy = [...original];

console.log(copy); // [1, 2, 3]

Adding elements:

const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5];

console.log(moreNumbers); // [1, 2, 3, 4, 5]

Merging arrays:

const a = [1, 2];
const b = [3, 4];
const combined = [...a, ...b];

console.log(combined); // [1, 2, 3, 4]

Using map() to Transform Arrays

The map() method lets you apply a function to every element in an array and returns a new array.
Example: Multiply each number by 2

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);

console.log(doubled); // [2, 4, 6]

In React, map() is commonly used to render lists of components:

const items = ['pen', 'notebook', 'eraser'];

return (

    {items.map((item, index) =>
  • {item}
  • )}


);

Top comments (0)

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