简体   繁体   中英

React Avoid Re-Render for Functional Component

I am using Hooks and how can I avoid from re-render? My purpose of asking this quesiton, I am using scroll for overflow item from div height and when I focus on a item using onMouseOver, my funtional component is rendering itself and scroll is returning initial position. Therefore I dont delete last item of div. Could you any advice to avoid re-rendering?

My component:

 import React from 'react'

  type removeDisplayItem = {
    dataId: number;
    display: boolean
}

  const PlayerCalendar = () => {
  const [removeDisplayData, setRemoveDisplayData] = useState<removeDisplayItem>({ dataId: -1, display: false })

    const handleRemove = (dataId: number, display: boolean) => {

        const removeData = {
            dataId: dataId,
            display: display
        }
       
        setRemoveDisplayData(removeData)
    }

    const renderScheduleContentCell = (data: scheduleItem) => {
      
        return (
            <>
                <div className="cell-content-wrapper" style={removeDisplayData.dataId === data.id && removeDisplayData.display === true ? { display: "none" } : { display: "flex" }}
                    onMouseOver={() => handleDisplayRemove(data.id, true)}>

                    <div className="start-time-text">{moment(data.startTime).format("HH:mm")}</div>
                    <div className="dash"> - </div>
                    <div className="end-time-text"> {moment(data.endTime).format("HH:mm")} </div>

                </div>

                <div className="cell-content-wrapper" onMouseLeave={() => handleDisplayRemove(data.id, false)}
                    style={removeDisplayData.dataId === -1 ? { display: "none" } : removeDisplayData.dataId === data.id && removeDisplayData.display === true ? { display: "flex", justifyContent: "space-between", backgroundColor: "#8c9296", color: "white", cursor: "pointer" } : { display: "none" }}
                    onClick={() => setCalendarRemoveItemConfirm(true)}>

                    <div className="dash"> &nbsp;</div>
                    <div className="start-time-text">Remove</div>
                    <div className="end-time-text"><i className="fas fa-trash-alt"></i></div>

                </div>

            </>
        )
    }

 return (
          {renderScheduleContentCell(exampleData)}
      )
  }
  
  export default PlayerCalendar;

Try to use the memo HOC and wrap it around PlayerCalendar component.

React.memo can be use to optimize your component. When you have the same props / state it can be used to memoize the data .

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