Redux Middleware and Redux Hooks - 401-advanced-javascript-davetrost/alchemy-fsjs-fall-2019 GitHub Wiki

Redux Middleware and Redux Hooks

Middleware

This seems to be used for logging and for asynchronous calls. Logging makes sense. I can see where a deployed app could benefit from logging Redux state changes somewhere for later review. However, at my current level of development, I get logging for free from the Redux Dev Tools in Chrome. Asynchronous calls were very easy in React with custom hooks. I found an example here of asynchronous calls in Redux using middleware (specifically, thunk). There will also be an example in Class 41 from the repo for Alchemy Career Track.

React Redux Hooks

the React-Redux package provides 2 hooks that can provide state to a component in a way that is slightly different than the mapSateToProps/mapDispatchToProps mechanisms. These functions make it so that Redux components look more like "react" components. I find them easier to read because all of the information is chronologically presented in the code.

  • Without Redux Hooks:
const Document = ({ markdown, handleChange }) => ({
  <div className={styles.Document}>
    <Editor markdown={markdown} updateMarkdown={handleChange} />
    <Preview markdown={markdown} />
  </div>
});

Document.propTypes = {
  markdown: PropTypes.string.isRequired,
  handleChange: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  markdown: getMarkdown(state)
});

const mapDispatchToProps = dispatch => ({
  handleChange({ target }) {
    dispatch(updateMarkdown(target.value));
  }
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Document);
  • With Redux Hooks
import { useSelector, useDispatch } from 'react-redux';

export const Document = () => {
  const markdown = useSelector(state => getMarkdown(state));
  const dispatch = useDispatch();
  const handleChange = ({ target }) => dispatch(updateMarkdown(target.value));
  return (
    <div className={styles.Document}>
      <Editor markdown={markdown} updateMarkdown={handleChange} />
      <Preview markdown={markdown} />
    </div>
  );
};
⚠️ **GitHub.com Fallback** ⚠️