Prajwal
Prajwal

Reputation: 4000

changing two props in react-redux using one action

I'm trying to implement the tick-tac-toe game of react tutorial with Redux. So far I've done this, which works fine, but renders the Board twice. Below is the app detail.

State
|
|--> Squares
|--> NextPlayer

I'm using AppReducer, which combines two separate reducers (squares and next player)

const appReducer = combineReducers({
    squares: squareReducer,
    NextPlayer: stateReducer
});

Both are props in component Board and has separate actions & reducers. and I'm calling the action using react-redux mapDispatchToProps like this.

dispatch(changeSquaresAction(id, next));
dispatch(changePlayerAction(next));

I'm creating Board HOC using connect and the state gets modified twice because I'm calling two actions.

My question is,

  1. Can I combine both Actions (in dispatch or somewhere else) keeping state as it is?
  2. Can I trigger the component render only once?
  3. Am I doing this correctly? I'm newbie in react.

Upvotes: 0

Views: 181

Answers (3)

Shirley
Shirley

Reputation: 190

Since you have two separate reducers that are combined, each time you dispatch an action both reducers are being called. So, for instance, if your action looks like

{type: 'CHANGE_PLAYER_ACTION', next: 2, id: 1} 

then both of the reducers will check if it matches that action type. That means you can just dispatch one action and in your squareReducer and stateReducer they can both have

case 'CHANGE_PLAYER_ACTION': 
//insert whatever needs to be done

Upvotes: 1

Rodius
Rodius

Reputation: 2311

You could use redux-batched-actions.

Upvotes: 0

jb cazaux
jb cazaux

Reputation: 320

i would create 2 reducers that match the same action.

And if you really want to render your component only once, look at the shouldComponentUpdate() method. But even if render() is called twice, it doesn t mean it is redrawn in the browser. React knows if DOM has changed or not. Look at the reconciliation algorithm.

React provides a declarative API so that you don’t have to worry about exactly what changes on every update. This makes writing applications a lot easier, but it might not be obvious how this is implemented within React. This article explains the choices we made in React’s “diffing” algorithm so that component updates are predictable while being fast enough for high-performance apps.

Upvotes: 0

Related Questions