관리 메뉴

Silver Library (Archived)

From class to functional component? 본문

F2. Problem & Solving/Data Structure

From class to functional component?

Chesed Kim 2023. 1. 24. 10:37
반응형

Let's see how it would look like with class and functional component each.

// class based component
class AnimeComponent extends React.Component {
	constructor(props) {
    	super(props)'
        this.state = { count: 0 };
        this.handleClick = this.handleClick.bind(this);
	}
    
    handleClick() {
    	this.setState(state => ({ count: state.count + 1 }));
    }
    
    render() {
    	return (
        	<button onClick={this.handleClick}>
            	Clicked {this.state.count} times.
            </button>
        );
    }
}

// functional component

import { useState } from 'react';

function AnimeComponent() {
	const [count, setCount] = useState(0);
    
    function handleClick() {
    	setCount(count + 1);
    }
    
    return (
    	<button onClick={handleCLick}>
    		Clicked {count} times.
        </button>
    );
}

functional component used useState hook to manage component state. This handleClick will act as an inline function within the component. This handleClick function will update the state by calling setCount with the new value in it.

 

Since functional components no longer use this keyword, it will not require to bind event handlers with consturctor.

 

In case I do need to use lifecycle methods like componentDidMount, componentWillUnmount, componentDidUpdate things (those are in class based component!), I can convert them to useEffect hook in functional component.

// Class-based component
class AnimeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: props.initialData };
  }

  componentDidUpdate(prevProps) {
    if (this.props.dataId !== prevProps.dataId) {
      fetchData(this.props.dataId).then(data => this.setState({ data }));
    }
  }

  render() {
    return <div>{this.state.data}</div>;
  }
}

// Functional component
import { useState, useEffect } from 'react';

function AnimeComponent({ initialData, dataId }) {
  const [data, setData] = useState(initialData);

  useEffect(() => {
    fetchData(dataId).then(data => setData(data));
  }, [dataId]);

  return <div>{data}</div>;
}

This example used useEffect hook in order to fetch new data. Once dataId prop is passed as the second argument to useEffect, this will only take action (effect) when dataId prop changes.

'F2. Problem & Solving > Data Structure' 카테고리의 다른 글

Soft and hard copy?  (0) 2023.01.10