What is a state in Redux?

Viewed 2125

I have googled, read and watched tutorials and for some reason, everyone expects you to know what a state is. Some slightly brush over it but don't really explain what it is. In the end, the whole explanation of what a state is becomes verbose with nothing really to pin point to and since Redux isn't bound to React and can be used in Angular too, I'd be very happy if someone explains to me and everyone else who is also wondering what a state is (preferably in Angular with an example).

6 Answers

What is a state in Redux?

State is a design pattern used to represent the state of an object. One of the Gang of Four's behavioral design patterns. It's not specific to Redux, which is just a centralized place to store data.


The Redux State is the God of your application. If you are an element and you want to know whether you are clicked (for example) now, you could ask State. It is a photograph of your application at a given time.

It stores all the information of your application. Imagine taking a picture of your application, it would have a clicked checkbox, a dropdown list enabled, a radio box disabled, etc. for example.

The state is an object that has all these information as properties. For example, { checkboxClicked: true}. In general, the object has a snapshot of your application at its current state.

When the user acts, by unchecking the checkbox, the state of your application should change. So let's do this:

{checkboxClicked: false}   // WRONG

State is immutable. This means that you cannot modify it (you can't modify a photograph, it belongs to the past).

So what do we do? We register reducers that handle the action caused by the user.

In this case, the reducer will take the action of unchecking the checkbox, and produce a new, fresh state, which will be exactly as the previous one, except from the property named checkboxClicked, which will be set to true now.


Alternative explanation:

State is the center of your world (application).

Imagine that your application has a checkbox. The information of whether this element is clicked or not can be modelled in the state object. Imagine it like this (rough intuition):

State = {checkboxClicked: false};

The above could be the initial state of your application.

When the user checks that checkbox, Angular dispatches an action. The information has to be updated in your state, but not at this particular one, since this state is gone, it belongs to the past!

Your application now has a checkbox clicked. You have to take a new photograph to depict the new information. State is immutable, you cannot modify it. In other words, you are not allowed to do this State.checkboxClicked = true;.

You produce a new, fresh State via a Reducer. A Reducer is a function that handles an action. In that case it will create a State object, where every property will be the same as before, and only checkboxClicked will be set to `true.

This will be the current State of your application, until a user acts.

Good question, we need state because how are we gonna save what’s happening with our dynamic application without it?

Think about it, if a user clicks a button, how does the app know what to do next? Before clicking — we have a default state and after the user has clicked the button, we change the state to represent what will happen next.

Example: we have a counter with a starting number at zero. The initial state is zero. The user clicks on the button. Hmm… what next? How are we gonna fit the pieces together and more importantly increment or decrement the number? We need some kind of dynamic mechanism to represent our actions and convert it into representational feedback/data. We call it State. Once you use state — you can’t live without it.

A state in Redux is a JavaScript object, where the internal state of the application is stored as its properties, e.g. which user is logged on. After having logged in, the user of your application may navigate to different pages in your application, but you need to remember somehow, who that user is. That piece of information is part of your application's internal state.

The state is then modified via reducers, never directly, by having them execute actions, the result being a copy of the previous state with the changes applied. For example, if the user logs in, you may issue an action of

var action = { type = 'USER_LOGIN', payload = 'john' };

which is sent to a userReducer. That reducer may then change the loggedInUser property of your state from, say, 'jane' to 'john'. The idea with state is to have a central place for all these pieces of information, so you have access to that data from anywhere in your app.

Think of state as a collection of global variables that you may read from at any time, anywhere, but that you can only write to by dispatching actions. If you were able to write to them as you please, this would get messy very quickly. By forcing you to dispatch actions the order in which the changes to these properties are applied is deterministic, making the app less error prone.

Since every change to a property needs to go through the reducer you can intercept that change by setting a breakpoint inside the reducer to see where the change comes from. If you could write to the state directly (which is the case with global variables), you'd have no way of knowing when and from where the change was applied, which can lead to hard-to-debug applications.

In information technology and computer science, a program is described as stateful if it is designed to remember preceding events or user interactions; the remembered information is called the state of the system.

From: https://en.wikipedia.org/wiki/State_(computer_science)

So, for example, you want to keep track of a counter and then you need something like this (in pseudocode, not Redux yet, example is below this example):

// 1. Initial state or value for the counter.
var counterState = 0;

// 2. Some functions to knows how to mutate/transforms the counter state.
function incrementCounter(prevState) {
  return prevState + 1;
}

function decrementCounter(prevState) {
  return prevState - 1;
}

// 3. Something that triggers this counter state mutatores based on user interactions.
var incrementButton = document.getElementById('plusButton');
incrementButton.onclick = function () {
  counterState = incrementCounter(counterState);
  console.log(counterState);
};

var decrementButton = document.getElementById('minusButton');
decrementButton.onclick = function () {
  counterState = decrementCounter(counterState);
  console.log(counterState);
};

Redux is a predictable state container for JavaScript apps.

From: http://redux.js.org/

In Redux, State means the same thing. Redux is just a library that allows you to keep track of state on your program using good software development practices using concepts like reducers (state mutators) and actions (user/system events).

The whole state of your app is stored in an object tree inside a single store. This means that you have a centralized placed with the whole state of your application.

The only way to change the state tree is to emit an action, an object describing what happened.

To specify how the actions transform the state tree, you write pure reducers. A pure reducer is a what is called pure function.

The following is a reducer, a pure function with (state, action) => state signature. It describes how an action transforms the state into the next state:

import { createStore } from 'redux'

function counter(state = 0, action) {
  switch (action.type) {
  case 'INCREMENT':
    return state + 1
  case 'DECREMENT':
    return state - 1
  default:
    return state
  }
}

// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(counter)

// You can use subscribe() to update the UI in response to state changes.
store.subscribe(() =>
  console.log(store.getState())
)

// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch({ type: 'INCREMENT' })
// 1
store.dispatch({ type: 'INCREMENT' })
// 2
store.dispatch({ type: 'DECREMENT' })
// 1

From: http://redux.js.org/

All answers are pointing towards the same direction which is a UNIVERSAL IMMUTABLE JAVASCRIPT OBJECT containing all the data of our app at a single point of time. Really looks like the $SCOPE variable in Angularjs 1.x .

A store holds the whole state tree of your application.

What is State? State represents the entire state of a Redux application, which is often a deeply nested object. The only way to change the state is to dispatch an action. Its an object with few methods on it.

You can read more here https://reduxsimplified.blogspot.com/2018/08/redux-store.html

Related