Redux Hooks in React: An Introduction

Breaking down Redux Hooks and how to use them in React

Redux Hooks: A Brief History

Redux hooks introduce new functionality

Understanding the useSelector Hook

What useSelector replaces

const mapStateToProps = state => ({ 
counter: state.counter
});
const MyComponent = connect(
mapStateToProps,
null
)(PresentationalComponent);

Basic usage of useSelector

const result:any = useSelector(selector:Function, equalityFn?:Function);
import React from 'react' 
import { useSelector } from 'react-redux'
const MyComponent = (props: any) => { const counter = useSelector(
state => state.counter
);
return(
<div>Counter: { counter }</div>
)
}
const Header = (props: any) => {  const header = useSelector(
state => (
{
username: state.user.username,
notifications: state.notifications.length
})
);
return(
<header>
<div>Welcome, {header.username}</div>
{header.notifications > 0 &&
<div className='notifications'>
You Have {header.notifications} Notifications
</div>
</header>
)
}
// relying on props to extract Redux store valuesexport const DisplayProduct = props => {
const product = useSelector(state =>
state.products[props.product_id]
);
return <div>{product.title}</div>
}

Reselect with useSelector

import { createSelector } from 'reselect'const MyComponent = (props) => {  // step 1: raw Redux store data  const cartItems = useSelector(
state => state.cart
);
// step 2: accumulate total value of items

const cartSubtotal = createSelector(
cartItems,
items => items.reduce((acc, item) => acc + item.value, 0)
)
...
}
const cartSubtotal = createSelector(
cartItems,
items => items.map(item => item.value * (20 / 100)),
(items, taxes) => {
const itemsSubtotal = items.reduce((acc, item) =>
acc + item.value, 0);
const taxTotal = taxes.reduce((acc, tax) =>
acc + tax, items);
return itemsSubtotal + taxTotal;
);
// take shipping cost from Redux storeconst shippingCost = useSelector(
state => state.shipping
);
// add shipping cost to cartSubtotal valueexport const cartTotal = createSelector(
cartSubtotal,
shippingCost,
(subtotal, shipping) => ({ total: subtotal + shipping })
);

Dispatching actions with useDispatch hook

// defining useDispatchimport React from 'react' 
import { useDispatch } from 'react-redux'
const MyComponent = (props) => {
const dispatch = useDispatch();
...
}
const SignInButton = (props) => {

const dispatch = useDispatch();

return (
<div>
<span>{value}</span>
<button
onClick={() => dispatch({
type: 'SIGN_IN',
payload: {
username: props.username,
password: props.password,
timestamp: (+ new Date() / 1000)
}
})
}>
Sign In
</button>
</div>
);
}
// src/actions/index.jsximport { SignInPayload } from '../types';export const setSignIn = (payload: SignInPayload) => ({
type: 'SIGN_IN',
payload: data
})
// src/types.tsxexport interface SignInPayload {
username: string;
password: string;
timestamp: number;
}
// src/SignInButton/index.jsximport { setSignIn } from '../actions';const now = (+new Date() / 1000);const payload = {
username: props.username,
password: props.password,
timestamp: now
};
...
<button
onClick={() => dispatch(setSignIn(payload))}>
Sign In
</button>
...

Memoizing useDispatch with useCallback

import React, { useCallback } from 'react' 
import { useDispatch } from 'react-redux'
const dispatch = useDispatch()const signIn = useCallback(
() => dispatch({ type: 'SIGN_IN' }),
[dispatch]
)
// definition of useCallback. `a` and `b` are dependenciesconst memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);

Using batch() for batching dispatch events

import { batch } from 'react-redux'
...
function SignIn() {const dispatch = useDispatch();batch(() => {
dispatch(setUserSignedIn())
dispatch(setAuthToken())
dispatch(setDashboardDefaultLanding())
});
...
}

Other Redux Hooks

import React from 'react'
import { useStore } from 'react-redux'
export const Debug_PrintStore = (props) => {
const store = useStore();
return <div>{store.getState()}</div>
}

In Summary

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store