20201011 TIL useState

ToastEggsToast·2020년 10월 11일
0

React

목록 보기
7/13

React Functional Component

useState? (feat. accordion)

원래 state는 class Component에서만 사용 가능했지만, functional Component에서도 사용할 수 있는 방법이 있다. 바로 useState를 이용해서!

import React, { useState } from 'react';

const Accordion = ({ items }) => {
    const [activeIndex, seetActiveIndex] = useState(null);
    const onTitleClick = (index) => {
        seetActiveIndex(index);
    }
    const renderedItems = items.map((item, index) => {
        const active = index === activeIndex ? 'active' : '';
        return (
            <React.Fragment key={item.title}>
                <div
                    onClick={() => onTitleClick(index)}
                    className={`title ${active}`}>
                    <i className="dropdown icon"></i>
                    {item.title}
                </div>
                <div className={`content ${active}`}>
                    <p>{item.content}</p>
                </div>
            </React.Fragment>
        )
    });
    return (
        <div className="ui styled accordion">
            {renderedItems}
        </div>);
}

export default Accordion;

위 코드는 useState를 이용해 state를 설정할 수 있게 해주고,
activeIndex를 state명으로, setActiveIndex를 setState명으로 사용해 준 경우이다.

위 이미지를 보면 아주 이해가 잘 될 것이다! :D

useState를 쓰면 functional Component에서도 state를 사용할 수 있으니 아주 좋아보이지만.. 숨겨진 작은 단점이 있다. 바로 setState처럼 한 번에 여러개의 state를 변경할 수 없다는 점이다.

// classComponent
class App extends React.Component {
  state={color:"red",content:"red color"};
  handleButton = () => {
    this.setState({color:"green",content:"green"});
  }
  render(){
    return (
      <div>
     	 <h1 style={{color: this.state.color}}}>{this.state.content}</h1>
     	 <button onClick={this.handleButton}>Change Color</button>
      </div>
  }
};

// functionaComponent
const App = () => {
    const [color, setColor] = useState("red");
    const [content, setContent] = useState("red color");
    const buttonHandler = () => {
        setColor("green");
        setContent("green color");
    }
    return (
        <div>
            <h1 style={{ color: color }}>{content}</h1>
            <button onClick={() => buttonHandler()}>Change Color</button>
        </div>
    )
}

useState와 비슷하게 useEffect, useRef 등이 있는데 이 친구들을 통틀어 리액트의 Hooks라고 이야기한다. :)

profile
개발하는 반숙계란 / 하고싶은 공부를 합니다. 목적은 흥미입니다.

0개의 댓글