简体   繁体   中英

Too many re-renders issues in react-hooks

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 });
      }
}, [])

the issue is the following code:

 try {
  } catch (e) {
    setError({ e: "에러가 났어요😥" });
  } finally {
    setLoading({ loading: false });
  }

Whenever your component renders, you change the state and it re-renders it. To aviod this you can use useEffect.

useEffect(() => {
  if(error){
   //set your states
 }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM