1

Please help me out to understand this case. According to Hooks:

When we declare a state variable with "useState", it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it.

on the other hand, The stateless component calculates the internal state of the component but does not have the authority to change state. but in blew example I update my const by splice and setData

import React,{useState} from "react";
import "./style.css";

export default function App() {
const [data, setData] = useState([
  { name: "first",id: 1},
  { name: "two", id: 2 }
]);
const addData = () => {
var newVal={ name: "Four", id: 4 };
data.splice(data.lenght,0,newVal);

setData([...data,{name:"three",id:3}]);

console.log(JSON.stringify(data))
};
return (
 <div>
   <ul>
     {data.map((item,index) => {
       return <li>{item.name} {index}</li>;
     })}
   </ul>
   <div onClick={()=>addData()} > add to list</div>
 </div>
);
}

I can't understand, How does splice work in function component(Hooks)? so why do we need to used setData?

you can watch my code enter link description here in stackblitz.com when click to add to list, both ways are work.

Thank you.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Eb Heravi
  • 398
  • 5
  • 15

0 Answers0