V
V
Vann Damm2020-12-23 12:04:33
React
Vann Damm, 2020-12-23 12:04:33

How does useCallback pass the new state to the custom hook in this case?

There is a "custom" hook useAction, which returns another hook, and it, in turn, dispatches the data to the redax store.
The essence of the question is this: How does the hook, which is in the body of my functional component, give access (pass) to the hook received when calling the custom hook, which is in the dependency array in the functional component hook, new data from the local state (menuState)? As I understand it, the functional component hook has access to menuState (obviously) , but how does actionCreator get it, just how does it take it from the context? or completely rewriting happens to the variable const actionCreator = useAction(changeMenuState,{menuState:!menuState},menuState); ?
Functional Component:

export const MenuBtn = (props) => {
  const [menuState,setMenuState] = useState(false);
 	const getMenuState = useSelector((state) => state.menu.menuState);
  useEffect(()=>{
 	   setMenuState(getMenuState);
 	},[getMenuState]);
 	const actionCreator = useAction(changeState,{menuState:!menuState},menuState);
  const changeMenuState = useCallback((elem)=>{
 		actionCreator()
 	},[actionCreator])
  
  return (<div>
</div>)

Custom Hook:
export const useAction = (action, data, deps = null) => {
  const dispatch = useDispatch();
  const actionCreator = useCallback(()=>{
    dispatch(action({...data}))
  },deps? [deps] : [dispatch])
  return actionCreator;
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Shcherbakov, 2020-12-23
@effect_tw

How does the hook, which is in the body of my functional component, access (pass) to the hook received when calling the custom hook, which is in the dependency array in the functional component hook, new data from the local state (menuState)?

So you yourself pass the value of menuState in the second parameter to useAction Or I did not understand the question :(
{menuState:!menuState}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question