2
votes

I am learning react hooks, and so far, I´ve seen that are a way to make react 'reactive' which it was not before this cool new thing.

I've also tried to share the state between different components using hooks, and when a component change any value inside the state, the other components get the updates. So that made me think, can Redux or any other state management solution be completely replaced by react hooks? Is there any pros and cons?

Anything I should consider before trying to migrate my redux based app to hooks? I am not a fan of big 3rd party libraries and if I can achieve the same goals with the tools that react can offer, why not?

2
As far as I can tell, hooks let you write components without classes. Whether you use redux or not is a separate question. - Chris G
Redux can be completely replaced by prop-drilling. These choices often aren't about can/can't, but the maintainability and robustness of different options. Besides, redux has its own hooks you can use with it react-redux.js.org/next/api/hooks - CollinD
I've been using hooks and I would say it is not really meant to replace redux. It is meant to replace the ES6 class style components. So far I have been able to implement everything with function components thanks to hooks and I love it. - Chris Rollins

2 Answers

7
votes

If your use of redux is only based on the need to avoid prop-drilling, then react context ( using hooks or not ) could be enough for you.

But to answer your question: no. You can totally implement your version of dispatch action and get state with context and hooks alone, without redux, but redux offer more to the table than them. Middleware, ability to persist the state of your app, easier debug, etc.

If your app doesn't require all the benefits that redux could provide, then don't use it. But the statement "can context + hooks replace redux?" is false.

0
votes

I've found this pattern to replicate my use cases of redux (code below).

The idea is that the setValue function fires an event with a parameter carrying the value and the event handler updates the hooks internal state.

import { useState, useEffect } from 'react'

export function useValue(name, initial) {
  const [value, _setValue] = useState(initial)

  function setValue(value) {
    const evt = new CustomEvent(name, {detail: {value}})
    window.document.dispatchEvent(evt)
  }

  useEffect(() => {
    function handleEvent (evt) {
      _setValue(evt.detail.value)
      evt.stopPropagation()
    }
    window.document.addEventListener(name, handleEvent)
    return () => {
      window.document.removeEventListener(name, handleEvent)
    }
  }, [])

  return [value, setValue]
}