Skip to content
This repository has been archived by the owner on Apr 3, 2024. It is now read-only.

nice way to use hooks as not intended #7

Closed
mohaalak opened this issue Apr 21, 2020 · 1 comment
Closed

nice way to use hooks as not intended #7

mohaalak opened this issue Apr 21, 2020 · 1 comment
Labels
invalid This doesn't seem right

Comments

@mohaalak
Copy link

the whole library wants to do something like this

function useEffectReducer(notReducer, initialState) {
  const [state, setState] = useState(initialState);
  effects
  const dispatch= (action) => {
    setState(notReducer(state, action, useEffect))
  } 
  return [state, dispatch];
}

but the React will raise error for this piece of code, cause you should not use hooks this way,
so we can add all functions with effect inside a list

function useEffectReducer(notReducer, initialState) {
  const [state, setState] = useState(initialState);
  const effects = useRef([])
  const exec =  (a) => effects.current.push(a);

  const dispatch= (action) => {
    setState(notReducer(state, action, exec))
  } 
  useEffect(() => {
      effects.current.forEach(a => a())
      effects.current = []
  }, [state])

  return [state, dispatch];
}

so now we can run our effects anywhere we want.
what is wrong with this code? say we animate something using jQuery inside our reducer then calling exec inside it or calling an API then after that call exec when the data received,
so you implement a library that everywhere in the codebase you can call useEffect.

do you know how much effort the React team has done so you can't use effects this way?

I think it is better that every action or side effect will be wrapped inside a Task monad or something like that so the reducer will return a tuple of state and effects

also, the reducer is not pure as I said in twitter and you blocked me, I hope you understand that you are an influencer in this community and saying something that is not correct make other people like me in a mistake.

nevertheless, I'm sorry if my behavior was not appropriate I was just wanted to inform you and others like me that our reducer function is not pure.

@davidkpiano
Copy link
Owner

The internal implementation of the reducer is pure, as I have explained. The "effect reducer" might not seem pure, but it is not used directly - it is wrapped by a pure reducer that does not execute side-effects; it only captures them.

Please write a failing test if there is an issue with this implementation.

@davidkpiano davidkpiano added the invalid This doesn't seem right label Apr 21, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
invalid This doesn't seem right
Projects
None yet
Development

No branches or pull requests

2 participants