Querying your Redux store with GraphQL

Using Apollo Client’s InMemoryCache and Local Resolvers, it’s possible to have it query your Redux store:

import store from "./Store";

const typeDefs = gql`
    type Query {
        users: [User]
    }

    type User {
        groups: [Group]
    }

    type Group {}
`;

const client = new ApolloClient({
    cache: new InMemoryCache(),
    typeDefs,
    resolvers: {
        Query: {
            users: () => store.getState().users,
        },
        User: {
            groups: user =>
                store
                    .getState()
                    .groups.filter(group => user.group_ids.includes(group.id)),
        },
    },
});

Neat “hack”. A shame the Local Resolvers are deprecated in Apollo 3.0 and will most likely be removed in a future version.

Querying your Redux store with GraphQL →
Apollo Client Local Resolvers →

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 →

Redux in 30 lines of PHP

To get the full details behind Redux, Sorin Nunca has recreated it using PHP:

As I usually try to understand the tools I’m using, the following tries to be a toy implementation of Redux in PHP, in the hopes of gaining a deeper understanding of the concepts behind Redux.

Also covers combineReducers.

Redux in 30 lines of PHP →

⁉️ Looking to get started with Redux? Egghead has a great video course by Redux’ creator Dan Abramov.

How to Implement Redux in 24 Lines of JavaScript

90% convention, 10% library

In this post Yazeed Bzadough walks you through creating your own Redux implementation.

// simplified createStore function
const createStore = (yourReducer) => {
  let listeners = [];
  let currentState = yourReducer(undefined, {});

  return {
    getState: () => currentState,
    dispatch: (action) => {
      currentState = yourReducer(currentState, action);

      listeners.forEach((listener) => {
        listener();
      });
    },
    subscribe: (newListener) => {
      listeners.push(newListener);

      const unsubscribe = () => {
        listeners = listeners.filter((l) => l !== newListener);
      };

      return unsubscribe;
    }
  };
};

How to Implement Redux in 24 Lines of JavaScript →

Manage React State with zustand

Small, fast and scaleable bearbones state-management solution. Has a comfy api based on hooks, that isn’t boilerplatey or opinionated, but still just enough to be explicit and flux-like.

import create from 'zustand'

const [useStore] = create(set => ({
  count: 1,
  inc: () => set(state => ({ count: state.count + 1 })),
  dec: () => set(state => ({ count: state.count - 1 })),
}))

function Counter() {
  const { count, inc, dec } = useStore()
  return (
    <>
      <h1>{count}</h1>
      <button onClick={inc}>up</button>
      <button onClick={dec}>down</button>
    </>
  )
}

Here’s where things get interesting: To use parts of the store in child components, call the useStore hook, selecting the piece you need from it — no providers needed:

function Counter() {
  const count = useStore(state => state.count)
  return <h1>{count}</h1>
}

Installation per NPM/Yarn:

npm install zustand

Zustand – Bear necessities for state management in React →

🌐 In case you don’t get the name: Zustand is German for State.

Handling Redux Side Effects with redux-observable


To handle Redux side effects, I (and others) prefer to writing sagas with redux-saga .

After @duivvv mentioned it to me on Twitter redux-observable also caught my eye. At the core site RxJS 5 and the concept of Epics which take a stream of actions and return a stream of actions. The library is used extensively over at Netflix where it was created by Jay Phelps and (now Googler) Ben Lesh.

Here’s an example Epic which listens for a SEARCH action, and then actually performs the actual search (until it is cancelled):

const searchEpic = (action$, store) =>
  action$.ofType('SEARCH')
    .map(action => action.payload)
    .debounceTime(400)
    .switchMap(query => 
      ajax.post('http://localhost:8080/search', {query})
        .takeUntil(action$.ofType('CANCEL_SEARCH')))
    .map(res => ({type: 'SEARCH_DATA', result: res.response}))

💁‍♂️ If you’re entirely not familiar with RxJS then watch this ”RxJS Observables Crash Course” video

Next to some proper documentation there’s also a good introductory video available:

redux-observable
Understanding RxJS and Redux-Observable →

Related: Using RxJS and CSS Variables it’s very easy to create “Reactive Animations”

Inspecting Redux Stores in Production, without the Redux Devtools


Checking out the Redux Store of Soundcloud Redux

Back in the day I learnt a lot by hitting CTRL+U (View Source) on websites. Nowadays I still check the source code of some apps, yet it’s become a tad more difficult for some specific things.

When it comes to React apps that use Redux I like to see how they’ve set up their store. If the developer has enabled integration with the Redux Devtools I can use just that. When they haven’t (because: production) I manually look up the store and then retrieve it’s state.

To look up the store, use the React DevTools. Traverse the Component Tree until you stumble upon the element with a store prop. This usually is high up the tree.

💁‍♂️ The regular DevTools provide you the $0 command in the console to get the most recently selected element or JavaScript object, the React DevTools provide the $r command to get the most recently selected React Component.

With the correct component selected, getting the contents of the store is very easy thanks to the $r command:

$r.store.getState();

Dispatching actions also is a breeze:

$r.store.dispatch({
    type: '…',
    payload: {
        …
    }
});

Happy inspecting 🙂

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

10 Redux tips to scale your dev team

Recently I landed a gig at a company to help their team out with their React work (using Redux). This list of tips – save for number 10 – resonates quite well with what I’ve been introducing there:

  1. Plan 1 day of training per developer dedicated to Redux
  2. Integrate Redux-dev-tools as early as possible
  3. Use action creators
  4. Organize your file system with Redux Ducks
  5. Write unit tests, it’s *free*
  6. Make general APIs using payload-based action creators
  7. Anticipate that you will have a lot of async-handling code
  8. Normalize your state like a database
  9. Use selectors
  10. Flowtype, Reasonml or Typescript can really help

10 Redux tips to scale your dev team →

How to use Redux in highly scalable JavaScript applications

Alexis Mangin:

I have recently worked on the first version of a React-Native mobile app for one of my clients, which desired to architecture the app in a scalable way for a painless experience to add new features later. I believe we should always think about app architecture that way as it can always scale up later on, and I think it is a great idea to show you how I managed it on the Redux side of things with a few examples of code. Be inspired and adapt it to your own need.

His technique revolves around grouping your code per feature, not per function. These features then get assembled by applying the concept of reducer composition:

[Each] feature’s reducer then gets used by its direct parent’s feature reducer or in the root reducer if it’s defined at the global level.

How to use Redux on highly scalable JavaScript applications? →

Scaling your Redux App with ducks

It’s one of these things I too keep struggling with from time to time: do you organize your project files per type/functionality, or per feature?

Alex Moldovan from FortechRomania:

Our approach starts from the need to isolate the React code into a single folder — called views — and the redux code into a separate folder — called redux.

Inside the views folder, we prefer a function-first approach in structuring files. This feels very natural in the context of React: pages, layouts, components, enhancers etc.

Then, inside the redux folder…

Per feature a “duck folder” is created, containing actions, reducers, selectors, etc. for said feature:

duck/
├── actions.js
├── index.js
├── operations.js
├── reducers.js
├── selectors.js
├── tests.js
├── types.js
├── utils.js

Might give this kind of structure a try for the next React+Redux project …

Scaling your Redux App with ducks →