How to use hook in class component in reactjs

Srecko Kostic
1 min readOct 10, 2023

Convert the hook to a component and wrap the child in it. This article solves a problem with an example of how to use a hook such as useState in a class component. It works for other hooks as well.

Run the code here: https://codepen.io/Flexos96/pen/bGOzOxr?editors=1010

Read the code here:

Why does it work? The component children prop may take a function. We take advantage of that and use functional component to store state, we provide state and setState and we can use those in the child component.

This pattern is very powerful. Patterns are powerful. Learn and explore many different patterns. Thank me later.

Where can I use this pattern?

If you want to use a hook where you CAN NOT use a hook BUT CAN USE COMPONENT, simply TURN THE HOOK INTO A COMPONENT.

For more of my experiments, visit: https://github.com/srele96/sk-experiments

--

--

Srecko Kostic

I create content from my perspective on topics I learn. Some information may be incorrect, but I hope some find my content useful.