Replacing redux with react hooks and context (part 2)

Richard Oliver Bray
Feb 9 · 8 min read

Go to Part 1 →


Some styling

font-size: 10px;
import './index.css';
Rick and Morty scrolling

Adding favourites

<button type='button' onClick={() => toggleFavAction(episode)}>
Fav
</button>
const toggleFavAction = episode =>
dispatch({
type: 'ADD_FAV',
payload: episode
});
case 'ADD_FAV':
return {
...state,
favourites: [...state.favourites, action.payload]
};

Removing favourites

case 'REMOVE_FAV':
return {
...state,
favourites: action.payload
};
<header className='header'>
<div>
<h1>Rick and Morty</h1>
<p>Pick your favourite episodes</p>
</div>
<div>
Favourite(s) {state.favourites.length}
</div>
</header>
{state.favourites.find(fav => fav.id === episode.id) ? 'Unfav' : 'Fav'}
style={{ display: 'flex', justifyContent: 'space-between' }

Splitting up our code

import React from 'react'export default function EpisodesList(props) {
const { episodes, toggleFavAction, favourites } = props;
}

Oh hello suspense and lazy

const EpisodesList = React.lazy(() => import('./EpisodesList'));
fallback={<div>Loading...</div>}
<EpisodesList {...props} />
const props = {
episodes: state.episodes,
toggleFavAction: toggleFavAction,
favourites: state.favourites
};

Adding some routing with Reach/Router

npm install @reach/router
<div>
<Link to='/'>Home</Link>{' '}
<Link to='/faves'>Favourite(s) {state.favourites.length}</Link>
</div>
<div>Favourite(s) {state.favourites.length}</div>
import { Link } from '@reach/router';

Moving things around

import HomePage from './HomePage';
import { Router } from '@reach/router';
<StoreProvider>
<Router>
<App path='/'>
<HomePage path='/' />
</App>
</Router>
</StoreProvider>

Adding our favourites page

import React from 'react';
import { Store } from './Store';
const EpisodesList = React.lazy(() => import('./EpisodesList'));export default function FavPage() {
const { state, dispatch } = React.useContext(Store);
const props = {
episodes: state.favourites,
toggleFavAction: toggleFavAction,
favourites: state.favourites
};
return (
<React.Suspense fallback={<div>Loading...</div>}>
<div className='episode-layout'>
<EpisodesList {...props} />
</div>
</React.Suspense>
);
}
<FavPage path='/faves' />
import FavPage from './FavPage';

Conclusion


Octopus Labs London

We're the fintech innovation unit of the Octopus Group. We're building smart financial products and using tech to drive cultural change. Want to join us on the journey?

Richard Oliver Bray

Written by

Front end developer @OctopusLabs. Novice photographer, speaker and player of video games.

Octopus Labs London

We're the fintech innovation unit of the Octopus Group. We're building smart financial products and using tech to drive cultural change. Want to join us on the journey?