Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is Redux and how does it work? Redux क्या है और कैसे काम करता है?

Answer
// Redux: Predictable state container
// 1. Action - describes what happened
const INCREMENT = 'INCREMENT';
const action = { type: INCREMENT, payload: 1 };

// 2. Reducer - takes state and action, returns new state
function counterReducer(state = 0, action) {
  switch(action.type) {
    case INCREMENT:
      return state + action.payload;
    default:
      return state;
  }
}

// 3. Store - holds application state
import { createStore } from 'redux';
const store = createStore(counterReducer);

// 4. Dispatch - send action
store.dispatch({ type: INCREMENT, payload: 1 });

// 5. Subscribe - listen to changes
store.subscribe(() => {
  console.log(store.getState());
});
Redux cycle:
Action -> Reducer -> Store -> Subscribe -> Component update

Was this answer clear?