Why to Use hooks instead of Class?

Why to Use hooks instead of Class?
0

Maybe my understanding is wrong but so far from Hooks ( useState, useEffect, useContext) what i get is that we use hooks so we can use useState, useEffect, useContext in functional componets. So my question is why shouldn’t i just make a class component instead?
sorry if my understanding is wrong and my question is stupid :stuck_out_tongue:

Nothing stupid about your question at all, it’s a perfectly good one. Hooks are for functional components to give them features that previously only class components could access, such as state, contexts, and so on. People used to writing functional components can keep using them that way without having to convert them to a class. Since the entire component is still just a single function, it’s possible to pull off advanced tricks using functional programming techniques to manipulate the components.

There’s nothing wrong with class components however, and everything hooks can do can also be done in a class component. React isn’t getting rid of class components, so keep on using them if they work best for you. Functional components (and the hooks that go with them) just give you a different way to organize your code, a way that some programmers such as myself find more intuitive than classes.

3 Likes

I recently started using hooks. Still undecided on how much of an improvement they are over class based components.

It is a bit of a learning curve but worth trying if only to get a better understanding of how React works.

Hey @oshikurou, your question contains 2 unrelated questions:

  1. Shall I use hooks?
  2. Shall I use function or class notation?

Now, answer to the first question is straight forward YES, because of compositional programming. Keeping it short, composing components with external services (hooks) is way more efficient, reliable and reusable. More about this here: https://www.youtube.com/watch?v=wfMtDGfHWpA

Unopinionated answer to your second question would be “You can choose either, whatever works better for you”. In my opinion - class, for 2 reasons:

  1. You let people understand:
    A. What is outcome of your class - React.Component instance vs. cryptic JSX return of function
    B. Why name starts with capital letter
  2. You make your code cleaner by injecting hooks with generally accepted approach - dependency injection

Why React team will never suggest using classes with hooks? Because then it will start looking A LOT like Angular… :wink:

Here’s how you can/should combine hooks and classes:

import React from 'react';
import { useFetch } from 'react-fetch-hook';
import { useSelector, useDispatch } from 'react-redux';

class TodoList extends React.Component {
  constructor() {
    /* Create component */
    super();
    /* Inject hooks */
    this.fetch = useFetch;
    this.select = useSelect;
    this.dispatch = useDispatch;
    /* Select part of the store needed */
    this.todos = this.select(store => store.todos);
  }

  async componentDidMount() {
    const todos = await this.fetch('pathToTodos');
    this.dispatch({ type: 'LOAD_TODOS', payload: todos });
  }

  render() {
    return this.todos.map(({ id, text }) => <div key={id}>{text}</div>);
  }
}
2 Likes

Thank you for your answer!
So how do i decide whether to use a functional component or a class? Or is it irrelevant?
Also do you have any recommendations on any react ebook where i can learn some theory on react and how to use it best?

Thank you for your answer!
So its totally up to me whether i wanna use a class or a function with hooks? Aren’t there any “rules” i better follow to decide that?

The good thing about React, that it’s a library and not a framework, so pretty much “if it works - it works”. If you buy a hammer and find it useful to open bottles - good for you! Hammer will not restrict that :wink: It’s per user/team decision.

1 Like

also, why would anyone need to combine hooks and classes?

Hooks make it possible to use function components for situation where you previous needed a class.

There are many benefits to usings functions instead of classes. Here are some of the pro’s

  • functions are more lightweight in JavaScript. Classes carry around extra functionality like methods and properties mostly related to inheritance and the prototype chain. Things you don’t need in React. Also classes don’t really exist in JavaScript, they are sintactical sugar to make it easier to set up objects with inheritance and other functionality
  • functions don’t have the this keyword which makes it easier to grasp for beginners
  • functions make use of closures. Benefits of closures is that they are memory efficient. Closures are for example one of the reasons eventhandlers with setTimeOut or debounce will give you the expected result while with classes you have to write extra code for this.
  • funtions are written with less code (no this keyword, destructuring parameters), so are cleaner and easier to read/understand. This point is somewhat subjective since programmers that come from an OOP based language probably will find it easier to read classes

if you want more info I would recommend the following resources:

It is not needed to use a Class anymore in React. My personal opinion is that there is also no good reason anymore to write Classes anymore in React. I expect eventually the classes functionality will in the future be seperated from the main React library

the same component could be written like this as a function (so the topic starter can compare):

  const TodoList = () => {
    const todos = useSelect(store => store.todos)
    const todoData = useFetch('pathToTodos')

    useEffect(()=> {
        todoData && useDispatch({ type: 'LOAD_TODOS', payload: todos })
    },[todoData])

    return todos.map(({ id, text }) => <div key={id}>{text}</div>)
  }

You need to learn to use both because older repos, which for various reason may not have an updated version React, can not take advantage of hooks.

CORRECTION:
React not only won’t suggest using hooks with classes, it will actually throw, so no hooks in classes

So consider my example as just a experimental pseudo-code, that will never run :wink:

LOL @ mutable this… made my day :wink: