Skip to content

[v7-hooks] A simplier approach to hooks #1306

@sz-piotr

Description

@sz-piotr

I would like to propose a simple approach to integrate redux with react hooks.
The entire library code:

import { Store, Action, Dispatch } from 'redux'
import { useState, useEffect } from 'react'

export function createUseRedux <S, A extends Action> (store: Store<S, A>) {
  function useRedux (): [S, Dispatch<A>]
  function useRedux <T> (selector: (state: S) => T): [T, Dispatch<A>]
  function useRedux (selector?: Function) {
    const [state, setState] = useState(() => store.getState())
    useEffect(() => store.subscribe(() => setState(store.getState())), [])

    return [selector ? selector(state) : state, store.dispatch]
  }

  return useRedux
}

Usage:

// hooks.ts
import { createUseRedux } from 'react-redux'
import { store } from './store'
export const useRedux = createUseRedux(store)

// MyComponent.ts
import { useRedux } from './hooks'
const [value, dispatch] = useRedux(state => state.value)

Pros

  1. Fully typed store access (a big plus for ts users)
  2. Only one hook
  3. Very little code

Cons

  1. There might be some ineficiencies in the implementation

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions