Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
sz-piotr opened this issue Jun 10, 2019 · 2 comments
Closed

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

sz-piotr opened this issue Jun 10, 2019 · 2 comments

Comments

@sz-piotr
Copy link

sz-piotr commented Jun 10, 2019

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
@timdorr
Copy link
Member

timdorr commented Jun 11, 2019

We already tried and rejected a useRedux Hook. See #1252. Hooks are designed to be small and composable. A single API creates an opinionated structure and forces us to reject many common edge cases.

@timdorr timdorr closed this as completed Jun 11, 2019
@sz-piotr
Copy link
Author

I see. Thanks for the reply :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants