All Articles

How I add objects in the state array with React Hooks and TypeScript.

⁉️ Why?

I don’t mutate non-primitive values in states directly. Never ever. This can provide many problems in React backstages.

💻 How?

I use the useState hook to handle my state updates for simple cases. I prefer to use Types or Interfaces to declare non-primitive states. Also, I can add the initial state:

type Fruit = {
  id: string;
  title: string;
};

const initialFruits: Fruit[] = [
  {
    id: 'fruit1',
    title: 'Apple',
  },
  {
    id: 'fruit2',
    title: 'Orange',
  },
];

useState returns the state value and the function to update it:

const [fruits, setFruits] = useState(initialFruits);

// Logs the fruits state.
console.log(fruits);

// Adds a new fruit in the state.
const handleAddFruit = (fruit: Fruit) => {
    setFruits((prevFruits) => [
      ...prevFruits,
      fruit,
    ]);
  };

📌 Example!

The simple React component example:

import React, { useState } from 'react';

type Fruit = {
  id: string;
  title: string;
};

const initialFruits: Fruit[] = [
  {
    id: 'fruit1',
    title: 'Apple',
  },
  {
    id: 'fruit2',
    title: 'Orange',
  },
];

export const App: React.FunctionComponent = () => {
  const [fruits, setFruits] = useState(initialFruits);
  const [fruit, setFruit] = useState('');

  const handleAddFruit = (title: string) => {
    setFruits((prevFruits) => [
      ...prevFruits,
      {
        id: `fruits${fruits.length}`,
        title,
      },
    ]);
    setFruit('');
  };
  return (
    <div>
      <input type="text" value={fruit} onChange={(event) => setFruit(event.target.value)} />
      <button onClick={() => handleAddFruit(fruit)}>Add</button>
      <ul>
        {fruits.map((fruit) => (
          <li key={fruit.id}> {fruit.title} </li>
        ))}
      </ul>
    </div>
  );
};