Morteza Ebrahimi
Morteza Ebrahimi

Reputation: 760

How to access to new state of useReducer inside custom hook's function

I have a custom hook that uses useReducer.

function useMyCustomHook() {
   const [state, dispatch] = useReducer(EntityReducer, initialState);

   // console.log(state); // 1- state is up to date here

   const customDispatch = (action) => {
       dispatch({ ...action }); // first call EntityReducer by action.type

       //2- I use state and dispatch here(for example:use state for call an api, then dispatch response)
       // but the state is previous not new state?

       switch (action.type) {
           case "something":
               // use dispatch and state here                     
               return state;
       }
   }

   return [state, customDispatch];
}

use custom hook:

function HomePage(props) {
    const [state, dispatch] = useMyCustomHook();

    // for example use dispatch on click a button

    return (<div>...</div>)
}

Problem: the state is prev state inside customDispatch. How can I fix this?

Thanks in advance.

Upvotes: 2

Views: 1730

Answers (1)

mojtaba.ebra
mojtaba.ebra

Reputation: 121

As far as I realized your state staled in react-hooks(captured by closure).

Then you have these solutions:

1-useEffect with dependencies

useEffect(() => {
 // state will be updated here
 // declare 'customDispatch' here
}, [state,...]);

2-useRef inside useMyCustomHook like:

const [state, dispatch] = useReducer(EntityReducer, initialState);
const stateRef=useRef(state);

useEffect(() => {
        stateRef.current=state;
});

const customDispatch = (action) => {
// use state.current instead of state(state.current will be updated)
}

Upvotes: 5

Related Questions