DEV Community

Eelco Verbrugge
Eelco Verbrugge

Posted on • Edited on

React class to functional: states

In 2018 React introduced Hooks. "They let you use state and other React features without writing a class." Hooks can be used in functional components but a lot of projects are still written in class components.

In this serie I'll explain how easy it is to convert/refactor your class component to a functional component so you can use Hooks.

States

class component

import React from 'react';
import {Button} from "react-bootstrap";

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            show: false
        }
        this.handleShow = this.handleShow.bind(this);
    }

    handleShow() {
        this.setState({show: true});
    }

    render() {
        const {show} = this.state;

        return (
            <>
                <Button onClick={this.handleShow}>Show</Button>
                {show && <h1>Awesome</h1>}
            </>
        )
    }
}

export default Example;
Enter fullscreen mode Exit fullscreen mode

functional component

const Example = () => {
  const [show, setShow] = useState(false);

  const handleShow = () => {
    setShow(true);
  }

  return (
    <>
      <Button onClick={handleShow}>Show</Button>
      {show && <h1>Awesome<h1>}
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

1. Extends
Functional components no longer need to extends from React.Component

2. Constructor
Where as a constructor is needed in a class component to set states, a functional component can use the "useState" hook. Just import this hook to use it import React, {useState} from 'react';

3. Passing Functions to Components
In class components it is necessary to pass functions to components in the constructor by .bind(this) in order to work. Not needed in a functional component anymore.

4. Function
Functions are written a little different. The good old myFunction() { ... } has been replaced by myFunction = () => { ... }

5. Variables
Not needed anymore to point out to this.state.myState, but just use myState

Top comments (0)