what happens after dispatch function and reducer function in react-redux?

suppose if i dispatch an action using dispatch() , i know that reducer() is called which has an action object and current state as parameters . i want to know what calls that reducer function ? which functions are called before reducer function and after dispatch function ? after reducer function returns the new state ,which functions are called after that ? where does this new state goes ? does usestate() and useselector() also returns something after reducer function returns new state ?

Upvotes: 0

Views: 2106

Answers (1)

Topsy
Topsy

Reputation: 1172

i want to know what calls that reducer function ? which functions are called before reducer function and after dispatch function

dispatch() indeed 'call' every reducers. It uses an event system and all reducers are listening to this event (this is all behind the scene).

Still, you can write a piece of code that will be inserted between the dispatch call and the reducers catching actions.

It's called a middleware.

A middleware can intercept any action triggered by a dispatch, also it has access to the store.

At the end of your middleware your just use a callback to tell the flow to continue. You need to pass your action to it so your reducers can finally be called and receive the action.

Here is an example of middleware that log any actions that are sent by any dispatch()

const logger = store => next => action => {
  console.log('dispatching', action)
  let result = next(action)
  console.log('next state', store.getState())
  return result
}

To make it work you need to pass your middleware to your redux configuration, so they can be called.

after reducer function returns the new state ,which functions are called after that, where does this new state goes ?

If you look at your redux configuration you'll see somewhere that you combine all of your reducers ( often called root reducer).

const combinedReducers = combineReducers({ reducerA, reducerB })
const store = createStore(combinedReducers )

Redux use this combination of reducers to fill the store, so anytime a reducer return it's result, it can be save in 'the store'

does usestate() and useselector() also returns something after reducer function returns new state ?

useSelector() is a hooks that has the ability to read in the store. (Store that contains the fresh result of your reducers and is updated every time there is a modification in the store)

useState() is not related to redux. It's related to React. With useState you can read and write in the local state of a component.

It returns you a piece a your state and a setter for this piece of state.

const {myPieceOfState, setMyPieceOfState} = useState({ something :'a default value for myPieceOfState'})

Upvotes: 2

Related Questions