1

One way I know how to use hooks inside a class component is to have an HOC which returns a functional component, inside of which we can call the hook and pass the prop to a class component. Look at How can I use React hooks in React classic `class` component? and answer by Joel Cox.

Now coming to the question, taking the example from https://reactjs.org/docs/hooks-custom.html#using-a-custom-hook, consider we have a hook useFriendStatus which accepts a friendID, has an effect to subscribe to that online status of that friend and cleans up on every re-render, so that for a new friendID, the hook can subscribe to the new friendID.

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  // Effect to subscribe to online status of friendID and unsubscribe on re-render

  return isOnline;
}

Can a class component use such a hook? In the HOC pattern, we are leveraging the mount cycle of the hook. Can we leverage re-rendering of hooks in a React class component ?

alchemist95
  • 759
  • 2
  • 9
  • 26
  • 4
    hooks is meant to be used only in the functional components . Class components has its own way of abstracting the logic either via HOC pattern or render props . – Shyam Aug 14 '21 at 09:34

1 Answers1

0

You really should not use your hook in a Class component at all (and definitely not in componentDidMount lifecycle method - likely throws an error), but you also cannot use your custom Hook within the useEffect of a functional component (will throw a React error stating this if you try)... part of the purpose/utility of creating is larger so that you can abstract out data fetching or other async calls from other components.

(Those components can still have other useEffects if necessary but should not contain custom Hooks)

sculs
  • 174
  • 5