React.JS / React Native : Class VS Hooks - Nicolas BAPTISTA

React.JS / React Native : Class VS Hooks

No matter if you are using React.JS or React Native, Javascript or Typescript, you can choose these 2 ways to manage the states.

Using Class OR using Hooks : What are the differences ?

Class

import React, { Component } from 'react'; 

[...]

class Button extends Component {
    constructor(props){
        super(props);

        this.state = {
            touched: false,
            selected: false,
        }
    }

  toggleTouched = () => {
    this.setState({
      touched: true
    });
  } 
    
    render(){ 
        return( 
            <button id="button" onMouseOver={this.toggleTouched} >
                click me!!
            </button>
        );
    } 
}

export default Button;

Using a class, you need to create a class that extends from a React Component. Like every class in every languages, you use the constructor to init the class. We use it to set the default values to our states. Moreover, we need to use “this” in that class to know that we are getting the values or the function in this class, this refer to the context.


Hooks

import React, { memo, useState, useEffect } from 'react'; 

[...]

const Button = memo((props) => {
  const [touched, setTouched] = useState(false);
  const [selected, setSelected] = useState(false); 
 
  const toggleTouched = () => {
    setTouched(true);
  } 

  return( 
     <button id="button" onMouseOver={toggleTouched} >
        click me!!
     </button>
  );
}); 

export default Button;

Same component, working the same too, but we need a bit less code.
We don’t need a constructor, to set the default value to our states, we just use the parameter of useState.
We don’t need the “this” keyword too, because we don’t are in a class anymore.

Instead of using setState, we use useState.
When it starts if “use…”, we are talking about hooks :
– useState : set a state with the name, the setter, the initial value
– useEffect : refresh if specific state is changed, we can use it as “ComponentWillMount” if we don’t give a state in 2nd param
– useRef : Reference for JSX
– useCallback, …etc.

Hooks seems to be the new best way to manage our states and you should use it as it may save a lot of times and lines in your code.

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments