January 20, 2022

What is Redux Library

When the application size grows in terms of codebase and number of components, the state management become one of the major issues. There are many different options to achieve centeral state management, one of which is the Redux library.

Redux is a library for managing and updating application state. It helps you manage the "global" state that is required by different parts of your application. Redux serves as a centralized store for state that needs to be accessed across the entire application. It asks you to follow certain restrictions and rules to ensure that the state can only be updated in a certain manner to achieve a predictable behavior.

Redux is useful in scenarios like:

  • Large amount of application state is needed to be shared in different parts of the app
  • The app state is updated frequently
  • Application has complex logic for state update
  • Large application codebase

Redux organizes the application state in a single data structure called as store. The different components of the application read the state from this store. Having the restrictive rules, it ensures that the store is never be mutated directly. A reducer function is used to make the new state by combining the old state and the mutations defined by the action.

Following are the basic elements of Redux:

  • Store

    The store is a single JS object. Usually you need to add a TypeScript file to the project with a new interface type declaration. This interface will contain all the properties that are required to keep in the store.

  • Actions

    Actions are plain JS objects that represent something that has happened or triggered. Can be compared to events.

  • Reducers

    A reducer is a function that specifies the logic how the state changes in response to an action (or event). An important point here is the fact that a reducer function does not modify the state, it always returns a new state object by merging the old state object with the new modifications.

    A reducer function must always be a pure function, means that the function must ensure that if the same input is provided, then always the same output is produced.

    For example, the following reducer function takes the old state and return the increment by adding 1 to the the state property count. This way, it will always return the same new state if the old state do not have any changes. Hence the the same input will always produce the the same output.

    function reducer(state, action) {
      switch (action.type) {
    	case: 'INCREMENT':
    	   return { count: state.count + 1 };
      }
    }
    	

References:

No comments:

Post a Comment