DEV Community

Katherine Kelly
Katherine Kelly

Posted on

Playing More Hooky with React

A few posts ago, I wrote Playing Hooky with React that touched on useState and useEffect and how my mind was blown away about the ability to use state and lifecycle methods without the need to write a class component. Though my mind is no longer blown, I still find exploring Hooks to be as fun as it was that first time I learned it. Since then, I have been exclusively building React and React Native projects using only function components and Hooks and don't see myself stopping anytime soon for the following reasons.

No More Class (Components)

Going off of my hooky theme, no more classes is as fitting as you can get. You can skip initializing a constructor, making sure you add this wherever appropriate, remembering to bind the event handlers, and using render() to return HTML.

All of your components need only be function components now. If you need to utilize local component state and/or lifecycle features, you can just "hook into" it through Hooks. Your components can stay more reusable and composable, and oftentimes will be less verbose than classes.

Hooks cover a lot of existing use cases for classes. The React docs do indicate there may be more Hooks coming out in the future that will be usable out of the box, such as a way to get previous props or state (like a usePrevious Hook). Currently in a function component, the only way to get previous props or state is manually with a ref, or you can extract the ref out into a custom Hook to be reused in other components.

Easy to Reuse Stateful Logic

If you need to reuse and share stateful logic between components, you can build your own custom Hook to save the day.

In the past, the most common ways to share stateful logic between components was with render props and higher-order components. Now with custom Hooks, it solves this problem without adding more components to your tree. Good stuff.

Perhaps my next post will dive deeper into the whys and hows of custom Hooks. See you next time!

Discussion (0)