Skip to content

Instantly share code, notes, and snippets.

@3nvi
Created March 5, 2019 20:18
Show Gist options
  • Save 3nvi/6d7cc3772b64fe2a10e294e9591b030d to your computer and use it in GitHub Desktop.
Save 3nvi/6d7cc3772b64fe2a10e294e9591b030d to your computer and use it in GitHub Desktop.
// action.js
const fireAction = item => ({ type: 'ACTION', payload: { item } });
// Option 1
import React, { useCallback } from 'react';
import { connect } from 'react-redux';
import { getItems } from './selectors';
function MyComponent({ item, fireAction, randomProp }) {
const fireActionWithItem = useCallback(() => fireAction(item), [item]);
return (
<React.Fragment>
<button onClick={fireActionWithItem}>{item}</button>
<ExpensiveComponent onClick={fireActionWithItem} />
</React.Fragment>
)
}
const mapDispatchToProps = {
fireAction
}
export default connect(null, mapDispatchToProps)(MyComponent);
// --------------------------------------------------------------
// Option 2
import React from 'react';
import { connect } from 'react-redux';
import { getItems } from './selectors';
function MyComponent({ item, fireActionWithItem, randomProp }) {
return (
<React.Fragment>
<button onClick={fireActionWithItem}>{item}</button>
<ExpensiveComponent onClick={fireActionWithItem} />
</React.Fragment>
)
}
const createFireAction = createSelector(
dispatch => dispatch,
item => item,
(dispatch, item) => () => dispatch(fireAction(item))
);
const mapDispatchToProps = (dispatch, ownProps) => ({
fireActionWithItem: createFireAction(dispatch, ownProps.item)
})
export default connect(null, mapDispatchToProps)(MyComponent);
@bastaware
Copy link

Seems option2 is missing import { createSelector } from 'reselect'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment