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;
functional component
const Example = () => { const [show, setShow] = useState(false); const handleShow = () => { setShow(true); } return ( <> <Button onClick={handleShow}>Show</Button> {show && <h1>Awesome<h1>} </> );}
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 itimport 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 oldmyFunction() { ... }
has been replaced bymyFunction = () => { ... }
5. Variables
Not needed anymore to point out tothis.state.myState
, but just usemyState
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse