본문 바로가기

react

리액트 _18_React_memo, callback

https://wastetime.tistory.com/33

**이 포스팅에 이어서 진행합니다.

 

리액트 _17_React_검색창 만들기

**이 포스팅에 이어서 진행합니다. https://wastetime.tistory.com/30 리액트 _16_React_useState, useEffect 1. public 밑에 music.json을 붙여넣는다. 2. index.html에 css를 넣는다. 클래스로 container 도 적..

wastetime.tistory.com

검색창에 글씨를 쓸 때마다 제목 색이 변경되게 해보자

 

H 변수에 색을 배열로 넣고 Math.random으로 랜덤으로 색이 나오게 적은 뒤 style안에 color를 넣는다.

//Memo 기능 사용
const  H = () =>{
    const color=["red","blue","green","yellow","pink"]
    const no = parseInt(Math.random()*5);

    return(
        <h1 className={"text-center"} style={{"color":color[no]}}>Music Top50</h1>
    )
}

위에는 memo를 사용하지 않았을 때이다.

memo는 함수의 리턴형을 기억한다. 

<memo를 사용했을 때> 

//Memo 기능 사용
const  H2= React.memo(()=>{
    const color=["red","blue","green","yellow","pink"]
    const no = parseInt(Math.random()*5);

    return(
        <h1 className={"text-center"} style={{"color":color[no]}}>Music Top50</h1>
    )
})

글씨 칠 때마다 색이 변하지 않는다. 

callback은 함수의 주소를 기억하는 것이다.

<callback을 사용했을 때>

*ss가 변경될 때만 호출하라는 뜻이다.

이전에 검색했던 기록들을 불러온다. 그래서 많은 데이터를 빠르게 출력해 줄 수 있다.

    //이벤트 등록
    const  handleUserInput =useCallback((ss)=> {
        setSs(ss);
    },[ss])

+) 전체 코드

import React, {useState, useEffect, useCallback, useMemo, Component} from "react";
import axios from 'axios';


//최종조립용
function App3() {
    //변수 설정
    const [music,setMusic]= useState([]);
    const [ss,setSs] = useState("");
    // 변수 초기값
    useEffect(()=>{
        axios.get('http://localhost:3000/music.json').then((res)=>{
            setMusic(res.data)
        })
    },[]) //Mount 할 때만 실행 => componenetDidMount
    //이벤트 등록
    const  handleUserInput =useCallback((ss)=> {
        setSs(ss);
    },[ss])
    return(
        <div className={"row"}>
            <H2/>
            <SearchBar ss={ss} onUserInput={handleUserInput}/>
            <div style={{"height":"30px"}}></div>
            <MusicTable music={music} ss={ss}/>
        </div>
    )

}
//음악리스트 큰 틀
function MusicTable(props) {
    let row=[];
    props.music.forEach((m)=>{
        if(m.title.indexOf(props.ss)==-1){
            return;
        }
        //배열에 추가
        row.push(<MusicRow music={m}/>)
    })
   return(
       <table className={"table"}>
           <thead>
               <tr className={"danger"}>
                   <th>순위</th>
                   <th></th>
                   <th>노래명</th>
                   <th>가수명</th>
               </tr>
           </thead>
           <tbody>
           {row}
           </tbody>
       </table>
   )
}
//음악 한곡씩
function MusicRow(props) {
    return(
        <tr>
            <td>{props.music.rank}</td>
            <td><img src={props.music.poster} width={"30"} height={"30"}/></td>
            <td>{props.music.title}</td>
            <td>{props.music.singer}</td>
        </tr>
    )
}
//검색바 useCallback 사용
function SearchBar(props) {
    const  onChange =(e)=>{
        props.onUserInput(e.target.value);
    }
    return(
        <table className={"table"}>
            <tr>
                <td>
                    <input type={"text"} size={"25"} className={"input-sm"} placeholder={"Search"} onChange={onChange}
                           value={props.ss}/>
                </td>
            </tr>
        </table>
    )
}

//Memo 기능 미사용
const  H = () =>{
    const color=["red","blue","green","yellow","pink"]
    const no = parseInt(Math.random()*5);

    return(
        <h1 className={"text-center"} style={{"color":color[no]}}>Music Top50</h1>
    )
}

//Memo 기능 사용
const  H2= React.memo(()=>{
    const color=["red","blue","green","yellow","pink"]
    const no = parseInt(Math.random()*5);

    return(
        <h1 className={"text-center"} style={{"color":color[no]}}>Music Top50</h1>
    )
})
export default App3;

 

반응형