What is the relationship between Closure and Redux under the hood?

Semih Özden
2 min readNov 13, 2023

--

While I was recalling my closure informations I recognize that I forget the key points. After a little bit research I understand and I come with the following real life scenario which we are facing in daily projects.

Closures are indeed used in Redux under the hood. Redux is a predictable state container for JavaScript applications, often used with libraries like React for building user interfaces. Closures play a crucial role in how Redux manages state and handles actions.

In Redux, the store holds the state of your application, and to update the state, you dispatch actions. Reducers are functions responsible for handling these actions and updating the state accordingly. Closures come into play because reducers are typically defined within the createStore function, which creates the Redux store.

When you define a reducer function inside createStore, it has access to the variables and parameters of its containing function, creating a closure. This allows the reducer to “close over” the initial state and handle actions with respect to that state.

Here’s a simplified example to illustrate the concept:

function createStore(reducer, initialState) {
let state = initialState;

function dispatch(action) {
state = reducer(state, action);
}

function getState() {
return state;
}

return {
dispatch,
getState,
};
}

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

const store = createStore(counterReducer, 0);

Then run the following codes to see the results line by line.

console.log(store.getState())
store.dispatch({type:"INCREMENT"})
console.log(store.getState())

In this example, the counterReducer is defined within the createStore function, creating a closure over the state variable. This allows the reducer to access and modify the state based on the dispatched actions.

So, yes, closures are used in Redux to maintain and update the state in a predictable manner.

--

--