简体   繁体   中英

How to prevent re-rendering in functional component in React

When I run this home page component is rendering many number of times. How to stop this unnecessary rendering. Please help me to solve this problem. Since we dont have ShouldComponentUpdate in functional component how to handle this problem. If possible send me live code example

const Home = (props) => {

  const [conversations,setConversations]=useState([]);
  const dispatch=useDispatch();
  const auth=useSelector(state=>state.auth);
  const conv=useSelector(state=>state.conversations);

  console.log(auth);
  

  useEffect(()=>{
    dispatch(getConversations(auth.user._id));
    setConversations(conv.conversations);
  },[auth,conv]);
  return(
    <>
    <Layout />
        <div className="messenger">
          <div className="chatMenu">
            <div className="chatMenuWrapper">
              <input placeholder="Search for friends" className="chatMenuInput"/>
              {
                conversations.map((c)=>{return <Conversations/>})
              }
              
            </div>
          </div>
          <div className="chatBox">
            <div className="chatBoxWrapper">
              <div className="chatBoxTop">
                <Message/>
                <Message own={true}/>
                <Message/>
                
              </div>
              <div className="chatBoxBottom">
                <textarea className="chatMessageInput" placeholder="write something"> 
                </textarea>
                <button className="chatSubmitButton">Send</button>
              </div>
            </div>
          </div>
          <div className="chatOnline">
            <div className="chatOnlineWrapper">
              <ChatOnline/>
            </div>
          </div>
        </div>
     </>
   )

 }

export default Home;

Best explanation here - https://reactjs.org/docs/hooks-reference.html#usereducer

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)

Note that React may still need to render that specific component again before bailing out. That shouldn't be a concern because React won't unnecessarily go “deeper” into the tree. If you're doing expensive calculations while rendering, you can optimize them with useMemo.

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