DEV Community

Discussion on: Your thoughts on React Hooks

sajjanbalar profile image


Recently, I was writing a new electron app with react. I decided to write it using Hooks. From my experience, I found that hooks are great for the most part. There are however some issues with using it in certain cases. In such cases, I find using classes more useful.

The one pattern that I found very painful to code in Hooks is when I want to write a custom hook that is passed a callback which it needs to call on certain conditions. I have found that if this callback uses a state variable or more. For every update of the state of this variable, I will have to pass my new callback to the hook.

This causes two issues.

  1. I have to remember every prop and state change that will be used by a function and write a useEffect hook to change the callback.

  2. The callback might be used in a complicated way inside the hook and it might be a pain to update it again and again.

I don't know if that makes sense, so let me give you an example.

I have written a hook that is responsible for handling an eventsource and invoking a callback whenever it receives a message. Let's call this useEventSourceManager.
I like the idea of useEventSourceManager because it gives me the ability to refactor all eventSource management into one hook.
Now, useEventSoucreManager is passed a callback "handleMessage" which is used to render ui for the new messages received.

My problem with hooks is basically that the following code won't work:

const someFunction = props => {
  const [condition, setCondition] = useState(false);
  useEventSoureManager(...someProps, ...someStateVariable, handleMessage);

  some other code that will change state of condition variable

  function handleMessage(){
    if(condition){ do something...}
    else{ do something else...}

The above code doesn't work because the handleMessage instance passed to useEventSourceManager always has the state variable "condition" set to false.

Also, I get why this happens. And the way to get around is to refresh the callback function. What I trying to point out is that that same code is much easier to write in classes.