loading...

re: How to convert a React Class Component to a Function Component VIEW POST

FULL DISCUSSION
 

Great article, Seb! A few considerations to add:

  • Functions can be written as constants, so when the component is super simple, it can have a simple definition as well:
const Greeter = ({ user, ...props }) => <div {...props}>Hi, {user}!</div>
  • useState is not a direct replacement for the setState method. It has some key differences (replaces the previous state instead of merging with it, re-renders only when is different, and so on).
  • The idea behind useEffect is to forget about the lifecycle, and only think about "side-effects" and the dependencies that trigger it, so deeper architecture changes need to be made beyond just "translating" lifecycle methods into useEffect.
 

Hey Lucas! thanks so much for the feedback. Whilst you're totally correct in all those things, I was trying to keep this example simple so that users who might not have as in depth knowledge could easily convert a component if they wanted to without getting too deep into it. Obviously there will be specific cases where these points matter, but I plan to address them with with some more complicated examples in the future.
Do you think I should rewrite some parts to include those points?

 

I don't feel like any rewrite is needed, you could just add that is not a 1:1 translation from class to a function, because it behaves differently. So the devs following this steps don't get confused if the component does something unexpected when turned into a function.

If I had to do that translation I would surely make it more complex, but your idea of keeping it simple is great for people new to the functional approach as an initial step 💖

code of conduct - report abuse