I want to use UseState to split the chat screen into Container and Presenter. But I've been going through too many rendering issues for two days now.
This is Container.jsx
import React, { useState } from "react";
import ChatsPresenter from "./ChatPresenter";
const ChatContainer = () => {
const [title, setTitle] = useState({
user: [""],
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
try {
} catch (e) {
setError({ e: "에러가 났어요😥" });
} finally {
setLoading({ loading: false });
}
return (
<>
<ChatsPresenter>{title.user}</ChatsPresenter>
</>
);
};
export default ChatContainer;
This is Presenter.jsx
import React from "react";
import styled from "styled-components";
import Loading from "../Loading";
const ChatsPresenter = ({ title, loading, error }) => {
return (
<>
{loading ? (
<Loading />
) : (
<>
<Container title="Kim" />
</>
)}
</>
);
};
export default ChatsPresenter;
const Container = styled.div`
font-size: 14px;
`;
This is index.jsx
import ChatContainer from "./ChatContainer";
export default ChatContainer;
How should I solve this problem?
The problem is that you update your state on every render, and this causes in a new re-render. You should wrap this in a \[useEffect\]
hook, if you only want to fire it once.
useEffect(() => {
try {
} catch (e) {
setError({ e: "에러가 났어요😥" });
} finally {
setLoading({ loading: false });
}
}, [])