Search code examples
javascriptreactjsreact-redux

What can go wrong when useRef is used with useSelector?


While I can access the store using thunks and/or global stores, I don't want to bind my component to the Redux store. Because the component will be used with other stores both inside and outside the project. The component has a number of children and passes props to them via the context API.

Since context APIs cause rerendering on child components, we employ the below approach to pass data from redux store to context APIs. This way, I can use dataRef.current whenever I need to access data in the redux store:

export const useData = () => {
  const dataRef = React.useRef();

  useSelector((state) => {
    dataRef.current = state;
  });

  return dataRef;
};

This works perfectly fine, But my concern is whether it will cause memory leaks or any other unknown problems.


Solution

  • It will likely cause things to not rerender in the right moment - since you leave the whole world of "letting React rerender" at that point in time. A change in the Redux store will not rerender your component any more.

    I think you need to reevaluate why you are doing this. This technique seems to bind your component to the Redux store just as much as just calling useSeletor would do. As long as your state structure has the value in the path you expect, you could also just call useSelector directly without any weird workarounds. That would work with any Redux store being present at that point in time.