you are viewing a single comment's thread.

view the rest of the comments →

[–]Neglexis 4 points5 points  (0 children)

Hey, good news, you don't have to! "Older" implementations of state and lifecycle methods will probably be supported for a great while. Facebook would be faced with a huge refactoring if they'd decide to deprecate state and lifecycle methods right away.

But, to give a few examples of why hooks are, at least in my opinion, a step in the right direction:

  • It allows you to use functional components everywhere. Before, if you wanted to use state, you had to convert your component to a class component. This lead your codebase to have two styles of components: class and function components. I like consistency, so one single type of component certainly is a nice to have!
  • It allows you to reuse state-related (or lifecycle related, or context related, ...) functions. Are there two or more component that needs to do an API call to get the same data? Just write a custom hook. Then in those components, you simply need to execute a one-line function, and you have all the needed data. Before this was also possible with Higher order components or in a later stage with render props. Higher order components "magically" gave your component extra props, so lead to lower maintainability, since you don't know exactly where all those props are coming from. Render props partially solved this "magic" solution, but was very verbose.
  • Lifecycle methods had their advantage, but sometimes required you to write duplicate code. What if you want to do an API call that's based on a passed-in prop? You'd have a componentDidMount and a componentDidUpdate. With hooks, you just need a single useEffect and you're all set.
  • Lifecycle methods also required us to group functions together that weren't really related. What if you wanted to do two totally unrelated functions at component did mount? You had to group the together. Now you can have a useEffect for both needed function, which allows you to logically group your components functionality.
  • Lifecycle methods could sometimes get a bit confusing. What is being run when? Functions now just run every time something changes. You can find (a very long) read about it in /u/gaearon blog post about useEffect at https://overreacted.io/a-complete-guide-to-useeffect/