Skip to content

Instantly share code, notes, and snippets.

@kpwahn
Last active July 27, 2020 21:17
Show Gist options
  • Save kpwahn/774cf41d5e382566650b71be8f1c2641 to your computer and use it in GitHub Desktop.
Save kpwahn/774cf41d5e382566650b71be8f1c2641 to your computer and use it in GitHub Desktop.

Three Tips For Optimizing Your react-redux Applications

Tip #1: When subscribing a component to the store, only subscribe to the specific data it needs

// Before
let selectedId = useSelector(state => state.list.selectedId);
let isSelected = props.id === selectedId;
// After
let isSelected = useSelector(state => state.list.selectedId === props);
  • Being specific in your subscriptions will help keep your components from re-rendering unecessarily.
  • Don't be afraid to write simple logic inside your of you selector functions.
  • Think about what the component really needs.
    • Does it need an id, or does it just need a boolean?

Tip #2: Avoid subscribing to objects in your store

// Before
let {list, name} = useSelector(state => state.list);
// After
let list = useSelector(state => state.list.list);
let name = useSelector(state => state.list.name);
  • When using the useSelector() hook, returning an object will always cause your component to re-render.

Tip #3: Subscribe more components (instead of passing props)

// Before
function Parent() {
  let name = useSelector(state => state.list.name);
  
  return (
    <>
      <FavoriteChild name={name} />
      <OtherChild />
    </>
  )
}
function FavoriteChild(props) {
  return <h2>{props.name}</h2>;
}
  • FavoriteChild and OtherChild will re-render every time name changes.
//After
function Parent() {
  return (
    <>
      <FavoriteChild />
      <OtherChild />
    </>
  )
}
function FavoriteChild(props) {
  let name = useSeletor(state => state.list.name);
  
  return <h1>{name}</h1>;
}
  • When name changes, only FavoriteChild will re-render.
  • Keep the subscription close to where the data is being used.
  • Don't be afraid to subscribe more components instead of leveraging what's already subscribed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment