Post

Chat - React.memo()

This post was migrated from Tistory. You can find the original here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const Messeges = () => {
        <>
            <S.Messages>
                {
                    reMsgArr.map((v: responseMsgDto[], idx) => {
                        return <Message key={idx} responseMsgArr={v} />
                    })
                }
                <div ref={chatRef}></div>
            </S.Messages>
            <S.InputDiv>
                <S.TextArea
                    value={inputMsg}
                    onChange={(e: any) => setInputMsg(e.target.value)}
                    onKeyDown={keyDownHandler}
                />
                <S.Send>
                    <S.SendBtn
                        onClick={sendHandler}>
                        Send
                    </S.SendBtn>
                </S.Send>
            </S.InputDiv>
        </>
    }

With the structure above, changing the textArea triggers setInputMsg, which re-renders Messages, and Message re-renders along with it.

The Message component has nothing to do with the inputMsg value, so there’s no reason for it to re-render.

1
export default memo(Messege);

So we export it wrapped with React.memo like this.

Now Message no longer re-renders when the textArea changes.

This post is licensed under CC BY-NC 4.0 by the author.