0

I have a stream of data that React accepts in the form of custom JS events. Each time the event fires, I need to update the value of a context provider so that the consuming components can re-render. However, I don't want all of the children to re-render, which is what's happening now because I am handling each new JS event with an update to the provider's state. I'm wondering how to avoid the children from re-rendering on this state change.

const DataListener = (props) => {
    const [data, setData] = useState([])
    const Data = createContext([]);

    useEffect(() => {
        document.addEventListener('newDataEvent', (e) => {
            setData([...data, e.detail]);
        })
    }, []);

    return (
        <Data.Provider >
            {props.children}
        </Data.Provider>
    );
}
  • https://stackoverflow.com/questions/57030018/react-context-with-hooks-prevent-re-render does this answer your question ? – BARNOWL Apr 25 '22 at 21:42
  • or you can look into this https://stackoverflow.com/questions/51317371/react-context-api-and-avoiding-re-renders – BARNOWL Apr 25 '22 at 21:44
  • 1
    in my opinion, their is better things to do with your time rather than memoizing this.. – BARNOWL Apr 25 '22 at 21:46
  • [Just to be clear, rerender in this context means calling render for all components, it doesn’t mean React will unmount and remount them. It will only apply the differences following the rules stated in the previous sections.][1] [1]: https://reactjs.org/docs/reconciliation.html#tradeoffs Reading this I think you might just work on a problem that is not actually a problem – Andreas.Ludwig Apr 25 '22 at 22:22

0 Answers0