Search code examples
reactjspublish-subscribereact-context

React Context API can't support efficient pub sub pattern


I'm using React's Context API to implement a simple pub-sub pattern. I have a list of 100 items with a few duplicates, and there's a like button on each of them, when I press the like button on an item, all of its duplicates should also show liked. Below is my functional component

function LikeButton({itemId}) {
  const {event, createEvent} = useContext(MyEventContext)
  const [isLiked, setIsLiked] = useState()
  console.log(itemId)
  const onPress = ()=>{
    // not updating local state directly, it's done
    // by useEffect below
    createEvent({itemId, isLiked:!isLiked})
  }
  useEffect(()=>{
    if (event.itemId===itemId){
      setIsLiked(event.isLiked)
    }

  }, [event])
  
  return <div>
    {isLiked?'liked':''}
    <button onPress={onPress}/> 
  </div>

}

This code works correctly but it's not efficient, the button press animation is very slow and it's because all of my 100 button components are invoked due to the eventContext even though there are only one or two items are actually rerendered. I guess it means Context API just can't implement pub-sub pattern very efficiently?


Solution

  • Yes this will cause all the LikeButton to re-render when an event is emitted, even if the change isn't relevant to the one clicked.

    You can use micro state management library like zustand to only update the components that are actually affected by a state change.

    A good reference book is "micro state managment" from Daishi Kato.