react.dev
react.dev copied to clipboard
[Updating Arrays in State] examples in the beta documentation are using impure function to explain concepts which doesn't seems right
Hi, learning react and going through the new react doc (beta). I finished reading about pure functions, but then in a later section (update arrays in state), it showcase multiple examples that seem contradictory to the concept of pure functions in React... OR I simply did not really understand that concept and If that is the case, I am sorry in advance.
let nextId = 0;
export default function List() {
const [name, setName] = useState('');
const [artists, setArtists] = useState([]);
return (
<>
<h1>Inspiring sculptors:</h1>
<input
value={name}
onChange={e => setName(e.target.value)}
/>
<button onClick={() => {
setName('');
artists.push({
id: nextId++,
name: name,
});
}}>Add</button>
//rest of the code...
isnt using a variable from outside (in this case: let nextId = 0) and just modifying it against the concept of pure function in react? If this is indeed an impure function, I just think it would be better to promote using pure functions in the visual examples just to not confuse new learners or at least mention that it was made on purpose.
The problematic part here is artists.push which is not "not what you want" according to the text above the example. Did you miss the text above the example, or is the question specifically about nextId?
The problematic part here is
artists.pushwhich is not "not what you want" according to the text above the example. Did you miss the text above the example, or is the question specifically aboutnextId?
Yes, the question is specifically about 'nextId'. I understand the problem is just to showcase how to not add items to an array. But to illustrate that, they use a variable outisde of the function and modify it inside of the function, wich makes the function impure if im not mistaken. React promote using pure function, so it just goes against what they preach to use impure function through out the documentation.
Correct me if im wrong, ty in advance.