3 ms·
I find it interesting that React ignores this advice about pure functions. From the react docs import React, { useState } from 'react'; function Exam
by gfxgirl 6y ago
I find it interesting that React ignores this advice about pure functions.
From the react docs
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
It's clear "Example" will be called every time it's rendered yet "useState" is NOT "pure". Some magic state is being kept because the first time it's called "count" will be initialized to 0 but after that it won't. Same arguments, different results = not "pure"
- brundolf 6y agoYeah, I tend to agree (and this is why I don't like hooks). I'll write pure functional components all day, but if I need to introduce state, I'm going to use a class component and just acknowledge that state as state and not try to pretend it's still just a function.
- anchpop 6y agoI use hooks because they cut down on boilerplate, not because I'm trying to pretend a component is just a function.
- neolefty 6y agoCorrect, `useState` (and `useEffect` and `useContext`) are not pure. They are ways of managing impurities while writing mostly pure functions.
- enneff 6y agoThe React model is actually superb at managing state. It makes you explicitly acknowledge it directly, and codifies it either with properties or useState. In practice it's a fantastic model, as it does let you write "mostly functions" as the article suggests, but you can't have a UI without state, so it's great that they make it easy to handle.