user8467470
user8467470

Reputation: 820

How to access redux connect mapStateToProps without a rerender

I am trying to use a mousedown event to close an autocomplete when the user clicks outside of the input.

code:

// listen to mouse clicking outside of autocomplete or input
useEffect(() => {
  document.addEventListener("mousedown", handleClickOutsideAutocomplete);

  return () => {
    document.removeEventListener("mousedown", handleClickOutsideAutocomplete);
  };
}, []);

const handleClickOutsideAutocomplete = (e) => {
  console.log("props:", props);
  const { current: wrap } = wrapperRef;

  if (wrap && !wrap.contains(e.target)) {
    setisOpen(false);
  }
};

This code runs as expected. However, when I try to access props on the mousedown event passed via react-redux connect, they are all null. The props passed from the parent component however are present. I have confirmed that on the initial render the react-redux connect props are there as expected.

I thought the mousedown event may be something to do with it so I tested accessing react-redux connect props using a timeout as follows:

useEffect(() => {
  const timer = setTimeout(() => {
    console.log("The connect props are all null", props);
  }, 5000);
  return () => clearTimeout(timer);
}, []); 

The react-redux connect props here are also null.

Is it possible to access connect props after the initial render, i.e., on a timeout or mousedown event?

Upvotes: 1

Views: 85

Answers (1)

Yousaf
Yousaf

Reputation: 29282

Problem is that you haven't added the handleClickOutsideAutocomplete function in the dependency array of the useEffect hook and because of the closure, event handler function doesn't sees the updated value of props.

Solution

Add the handleClickOutsideAutocomplete in the dependency array of the useEffect hook and also wrap handleClickOutsideAutocomplete in the useCallback hook to avoid running the useEffect hook everytime your component re-renders. Also don't forget to list the required dependencies in the dependency array of the useCallback hook.

useEffect(() => {
  ...
}, [handleClickOutsideAutocomplete]);        

const handleClickOutsideAutocomplete = useCallback((e) => {
  ...
}, [props]);                                 

React recommends to use exhaustive-deps rule as part of their eslint-plugin-react-hooks package. It warns whenever you omit or incorrectly specify a dependency and also suggests a fix.

Upvotes: 2

Related Questions