niks
niks

Reputation: 466

Is it mandatory to create action creator in redux layer?

I am new in redux library of react This is my code

// action creator
export function updateCategories(payload) {
  return { type: UPDATE_CATEGORY, payload };
}

// dispatch action creator 
dispatch(updateCategories({ list: data }));

But instead if I do like :

dispatch({ type: UPDATE_CATEGORY, payload });

so what is problem if I write action directly in dispatch without returning from function?

Upvotes: 0

Views: 295

Answers (2)

Roshan Raj
Roshan Raj

Reputation: 198

It helps in code re-usability. You can go through this link for more Info

Upvotes: 0

Jayce444
Jayce444

Reputation: 9063

Technically it's fine, you can dispatch straight from the component, but there's advantages of having actions creators, e.g.

  • It creates a intuitively named, reusable function for the dispatch, which you can import as needed, rather than manually dispatching all over the place. So if you want to change how the dispatch of a certain action works, you only have to change in the action creator and not go through all the places it's used and change each one
  • Simply dispatching something with a payload is fine, but you may also end up having logic to go along with that dispatch, like processing of the payload or fetching of data (using some tool like redux-thunk). It's better to have a single action creator where that's all defined that you can reuse throughout your application, rather than copy pasting that logic all over the place

Upvotes: 2

Related Questions