Why does this React component keep re rendering?

JoshuaRDBrown

I have this Post component which mounts if the user types in the Id of an existing post in firebase:

<Route path='/posts/:id' component={Post} />

However, console logging this component sends back the log indefinitely causing my browser and actions on the page to be really slow.

Heres the content of the Post component, I think it's something to do with the way I'm setting the state in useEffect but I'm not sure how to fix it. I've tried React.Memo and that didn't work:

function Post(props: RouteComponentProps<PostParams>) {

  const [postData, setPostData] = useState({ title: '', body: '', author: '', time: 0, photoURL: '', likes: 0, dislikes: 0});
  const [existingComments, setExistingComments] = useState([])
  const [commentContent, setCommentContent] = useState('');
  const isMounted = useRef(false);
  const db = fb.firestore();
  const ref = db.doc(`posts/${props.match.params.id}`)

  useEffect(():any => {
    isMounted.current = true;
    ref.get().then((doc: any) => {
      if(doc.exists && isMounted.current) {
        setPostData(doc.data().content);
        setExistingComments(doc.data().comments ? doc.data().comments : [])
      }
    });
    return ()=> isMounted.current = false;
  });

  return ( 
  //... some html that displays the information I've got from firebase

Thanks in advance for your help :)

Ramesh Reddy

When you're updating the state inside useEffect, this triggers a rerender because of the state change and once the component updates, useEffect runs again which changes the state triggering another render cycle, because of this pattern your component keeps rerendering.

You can add a dependency array to tell useEffect to run only when the component mounts and also when something changes, like this:

function Post(props: RouteComponentProps<PostParams>) {

    const [postData, setPostData] = useState({ title: '', body: '', author: '', time: 0, photoURL: '', likes: 0, dislikes: 0 });
    const [existingComments, setExistingComments] = useState([])
    const [commentContent, setCommentContent] = useState('');

    useEffect((): any => {
        const db = fb.firestore();
        const ref = db.doc(`posts/${props.match.params.id}`)
        ref.get().then((doc: any) => {
            if (doc.exists && isMounted.current) {
                setPostData(doc.data().content);
                setExistingComments(doc.data().comments ? doc.data().comments : [])
            }
        });
        return () => { };
    }, [setPostData, setExistingComments]);
    // setPostData, setExistingComments won't get a new reference for every render so they won't cause useEffect to run
    return (<></>);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why does my react component keep re-rendering?

How does React re-use child components / keep the state of child components when re-rendering the parent component?

React Component Re rendering

Why does the component is not re-rendering when i add @action decorator to an react event handler function

My React component is re-rendering, cannot figure out why

React Component does not re rendering when updating an object in state hooks

Why is this component not re-rendering

what is the right way to keep re-rendering component using setTimeout until prop changes in react js

Why is this react component rendering twice?

Why is a Component Re-Rendering done when changing the value of the props sent to child Component (react js)?

why child components div in react is not re rendering even though child component re renders at state change

React keep focus on re-rendering input

Why does button component in WP editor keep rendering anchor tag in front-end?

Why does a fraction of my Angular2 template keep re-rendering even if there are no changes?

Why is the (memoized) child component re-rendering?

Why is my functional component not re-rendering?

Why does my react state update on component re render?

React useEffect not re-rendering functional component

React UseContext change not re-rendering component

First click not re-rendering component in react

React Component keeps re-rendering/reloading

How to restrict react Component to Re-rendering,

React component not re-rendering on state change

Stop re-rendering the react functional component

React useState update is not re-rendering component

React component is re-rendering infinitely

ReactiveVar not re-rendering React component

React function component state not re-rendering?

React: componentDidMount + setState not re-rendering the component