简体   繁体   中英

react custom hook parent handler is not keeping custom hooks state

I'm trying to use custom hooks for view & other encapsulated functions.

But for some reason, I need to update data from parent. For this case, I delivered handler to custom hooks from parent and that handler is accessing hooks state.

/* this is hook */
    const customhook = useCustomHook({ init: true });
/* parent is calling hook function to update data */
const actionFromParent = e => {
    customhook.UpdateFromParentAction("First Data intialized");
  };

/* hook is assigning parent function */
const actionFirst = e => {
    customhook.SomeAction({
      data: "action first",
      init: true,
      handler: actionFromParent
    });
  };

/* inside hook, it is calling parent function */
{state.handler && <button onClick={state.handler}>Click Last</button>}

I attached sandbox code here: https://codesandbox.io/s/zen-napier-i6v5g?file=/src/custom.jsx:790-860

When actionFromParent creates a reference to this:

const UpdateFromParentAction = data => {
  setState({
    ...state,
    data
  });
};

The spread operator ...state refers to the values of the object precisely when that reference is created, not when it is eventually executed. If you want the setter to use the current values when it is executed, you can change it to this:

setState(s => {return {...s, data}});

More generally speaking, however, you should not use this method to get around the fact that you are passing stale values to your functions. Any logic which you want to be synchronised with the current state of the component should be wrapped in useEffect , useCallback , useReducer hooks etc. wherever possible.

Storing a component or hook's own functions in its own state is also a classic anti-pattern and to be avoided for this exact reason. You should return all the functions you need from the hook to the parent component and access them there - passing them back down is a recipie for disaster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM