blog podcast

The Beauty of Hooks

I’m really an amateur when it comes to React, but today as I read a bit more on hooks I couldn’t help but to admire the beauty of this feature.

I’m coming in from the side when it comes to React. Having most of my experience from working with AngularJS and kind of digging into Vue and sometimes React just briefly, I have an idea of what I expect `React to do for me, but I don’t have any in depth knowledge on how it really does this..

But I read about the functional components and the idea is clear enough to me. You write a pure function that returns some component. Then, when you want side effects you put that logic into this useEffect function. This covers up life cycle hooks like componentDidMount, componentDidUpdate and componentWillUnmount. The beauty is that this hook method gets triggered in all these cases. Furthermore, when it requires cleanup, you make it return a cleanup function, and react takes care of triggering that for you.

The beauty comes when you consider how these calls work in practice when the props change for your component. You realize that this really simple feature actually behave just like you would want.

Simplicity is beauty.

Code of the Day

From React’s documentation, explaining what is happening as a component that is using effects progress.

// Mount with { friend: { id: 100 } } props
ChatAPI.subscribeToFriendStatus(100, handleStatusChange);     // Run first effect

// Update with { friend: { id: 200 } } props
ChatAPI.unsubscribeFromFriendStatus(100, handleStatusChange); // Clean up previous effect
ChatAPI.subscribeToFriendStatus(200, handleStatusChange);     // Run next effect

// Update with { friend: { id: 300 } } props
ChatAPI.unsubscribeFromFriendStatus(200, handleStatusChange); // Clean up previous effect
ChatAPI.subscribeToFriendStatus(300, handleStatusChange);     // Run next effect

// Unmount
ChatAPI.unsubscribeFromFriendStatus(300, handleStatusChange); // Clean up last effect