In functional programming, a pure function returns the same value for the same arguments.
I'd like to hear tips for writing in React sometime. I definitely do a lot of thinking at some point.
For example, the onClickHandler
in the code below is not a pure function because it depends on an external state change.
const { useState } = require("react")
const Example = () => {
const [list, setList] = useState(["a", "b", "c", "d", "e"])
// Delete item from list, when button is clicked
// This function is non-puer because it uses external state (list, setList)
const onClickHandler = (e) => {
const newList = list.filter(item => item !== e.target.innerText)
setList(newList)
}
return (
<div>
{list.map((item, index) => {
return (
<div key={index}>
<button onClick={onClickHandler}>{item}</button>
</div>
)
}
)}
</div>
)
}
export default Example
- In this case, is it good to write these codes as pure functions?
- If not, should it be written as a pure function only at the component level?
I want to hear from programmers who are interested in React.