Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 modeExit 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 modeExit 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 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I write about coding subjects in order to expand my knowledge and hopefully others. Learning is creation, not consumption.
  • Location
    The Netherlands
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp