Skip to content

Instantly share code, notes, and snippets.

@kettanaito
Created February 3, 2020 11:27
Show Gist options
  • Save kettanaito/beb06ea82cef23ac0393bd67c932e432 to your computer and use it in GitHub Desktop.
Save kettanaito/beb06ea82cef23ac0393bd67c932e432 to your computer and use it in GitHub Desktop.
Getting started with Redux

Getting started with Redux

What is Redux?

Redux is a state management library. It implements a Flux pattern of handling the data and its primary feature is the reducing of the previous state to produce the next state.

What is Flux?

Flux is an architecture pattern to handle data fetching. It splits data fetching into separate layers, making them predictable, but also embeds a "model" and "controller" parts of traditional MVC into modern applications.

What makes Redux/Flux pattern?

  • Store. A single source of truth for the state.
  • Action. A function that describes a change in a state. May contain next data.
  • Dispatcher. A function that executes an Action.
  • View. Component(s) that depend on the Store.

Primitive example.

const store = {
  likes: 0
}

const addLike = () => {
  return {
    type: 'ADD_LIKE',
    amount: 1
  }
}

const dispatcher = () => {
  _dispatch(addLike())
}

const Component = () => {
  return <p>Likes: {store.likes}</p>
}

What problems do you see with such approach? Is there anything missing?

Install

npm install redux react-redux

Configuring a store

// src/store/index.js
import { createStore } from 'redux'

const initialState = {
  likes: 0
}

function likesReducer(state = initialState, action) {
  switch (action.type) {
    case 'ADD_LIKE':
      return state.likes + action.amount
     
    default:
      return state
  }
}

export default createStore(likesReducer)

Subscribing to the Store

import React from 'react'
import { useSelector } from 'react-redux'

const Component = () => {
  const likesCount = useSelector(state => state.likes)
  
  return <p>Likes: {likesCount}</p>
}

Creating an action

// src/store/likes-actions.js
export const addLike = () => ({
  type: 'ADD_LIKE',
  amount: 1
})

Dispatching an action

import React from 'react'
import { useSelector, useDispatcher } from 'react-redux'
import { addLike } from './store/likes-actions'

const Component = () => {
  const dispatch = useDispatcher()
  const likesCount = useSelector(state => state.likes)
  
  return (
    <div>
      <p>Likes: {likesCount}</p>
      <button onClick={() => dispatch(addLike())}>Add like</button>
    </div>
  )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment