I'm currently working on a project with React and Redux. I try (successfully so far) to write only stateless functional components. My code now starts having a lot of closures, especially when rendering lists.
Here is a simple example, which I tried to limit to 3 files and still fit in all the relevant code:
UsersList.js
import { connect } from 'react-redux'
import { userClickAction } from 'modules/users.js'
import UserItem from 'components/UserItem.js'
const UsersList (props) => {
const handleUserClick = (id) => () => {
props.userClickAction(id)
}
return (
<div className='userList'>
{props.users.map(user =>
<UserItem
user={user}
handleUserClick={handleUserClick(user.id)}
/>
)}
</div>
)
}
// use connect: userClickAction will be
// available in UsersList props
export default connect({}, {
userClickAction
})(UsersList)
UserItem.js
export default (props) => (
<div className='userList'>
<h2>{props.user.name}</h2>
<button onClick={props.handleUserClick}>
click!
</button>
</div>
)
modules/users.js
// ...
// ––– actions
export const handleUserClick = (id) =>
(dispatch) => {
dispatch({
type: USER_CLICKED,
payload: id
})
}
// ...
I'm a bit concerned about performances when using a lot of closures (in this example it can grow quickly with the number of users). The idea is to keep as much logic in the owner component (UsersList
). Is it a good/bad/neutral practice? Should I better write:
UserItem.js
export default (props) => {
const handleUserClick = () => {
props.userClickAction(props.user.id)
}
return (
<div className='userList'>
<h2>{props.user.name}</h2>
<button onClick={handleUserClick}>
click!
</button>
</div>
)
}
This does not require a closure, but still creates a function for each item in the list. Can this be handled completely differently instead?