cbdeveloper
cbdeveloper

Reputation: 31365

What is the main benefit of using action creators in Redux?

Let's say I have an input component that will update the state from its onChange handler.

function updateInputState(newvalue) {
  return({
    type: "UPDATE_INPUT_STATE",
    payload: newValue
  });
}

function InputComponent(props) {
  
  function onChange(event) {
    const newValue = event.target.value;

    // OPTION #1 - WITHOUT AN ACTION CREATOR. DISPATCH THE ACTION DIRECTLY
    dispatch({
      type: "UPDATE_INPUT_STATE",
      payload: newValue
    });

    // OPTION #2 - WITH AN ACTION CREATOR
    dispatch(updateInputState(newValue));

  }

  return(
    <input value={props.value} onChange={onchange}/>
  );
}

I think option #2 is more readable, so why would I use an action creator instead of a regular action dispatch?

Upvotes: 2

Views: 189

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

The main benefits are simplicity and maintenance, especially when it comes to async actions.

Action creators can also be asynchronous and have side-effects.

Therefore it simplifies the usage in component view:

// Lets say we suddenly want to make updateInputState async action
function InputComponent(props) {
  function onChange(event) {
    const newValue = event.target.value;
    // Edit its action creator implementation
    dispatch(updateInputState(newValue));

    // on the other hand, without action creator, you need to
    // change this code to async everywhere across the app
    dispatch({
      type: "UPDATE_INPUT_STATE",
      payload: newValue,
    });
  }

  return <input value={props.value} onChange={onchange} />;
}

Dave Ceddia makes this great point on maintainance: "when you copy-and-paste an action in multiple places, change is harder."

Notice that writing action creators is more like "an old API" you should use redux-toolkit now (2020).

Upvotes: 3

Related Questions