⁉️ 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',
},
{
id: 'fruit3',
title: 'Mango',
},
];
useState returns the state value and the function to update it:
const [fruits, setFruits] = useState(initialFruits);
// Logs the fruits state.
console.log(fruits);
// Deletes the fruit with the current ID.
const handleDeleteFeature = (id: string) =>
setFruits((prevFruits) =>
prevFruits.filter((fruit) => fruit.id !== id));
📌 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',
},
{
id: 'fruit3',
title: 'Mango',
},
];
export const App: React.FunctionComponent = () => {
const [fruits, setFruits] = useState(initialFruits);
const handleDeleteFeature = (id: string) =>
setFruits((prevFruits) =>
prevFruits.filter((fruit) => fruit.id !== id));
return (
<div>
<ul>
{fruits.map((fruit) => (
<li key={fruit.id} onClick={() => handleDeleteFeature(fruit.id)}>
{fruit.title}
</li>
))}
</ul>
</div>
);
};