React Redux with hooks

Jennifer Williams shows us how use Redux with Hooks

When I was first learning Redux I found all the moving parts and files incredibly hard to wrap my head around. Surprisingly, React hooks made the process of using Redux a lot easier for me.

The post provides us with a two-fold example. One “without hooks” and one “with hooks”. Here’s the “with hooks” version, which will look very familiar if you’ve already used both technologies (but not together):

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increaseVote, decreaseVote } from '../actions';

const AnimeCard = ({ anime }) => {
   const dispatch = useDispatch();
   const animesInStore = useSelector(state => state.animes);
   return (
      <div className="card">
         <p>{Object.keys(animesInStore).length}</p>
         <h2>Name: {anime.name}</h2>
         <p>Votes: {anime.votes}</p>
         <img src={anime.image} alt={anime.name}></img>
         <br />
         <button
            onClick={() => {
               dispatch(increaseVote(anime.id));
            }}
         >
            UpVote
         </button>
         <button
            onClick={() => {
               dispatch(decreaseVote(anime.id));
            }}
         >
            DownVote
         </button>
      </div>
   );
};

export default AnimeCard;

If you’re new to Redux, Jennifer has also written A Beginner’s Guide to Redux that you can check out.

React Redux with hooks →

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.