DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

How to create your own Redux Toolkit in raw js?

Redux Toolkit is a library designed specifically for React and Redux applications. It provides a set of utilities and abstractions to simplify common Redux patterns. It's not meant to be used in vanilla JavaScript without React. If you want a state management solution for vanilla JavaScript, you might want to explore other options like MobX, or consider implementing a custom solution.

That said, if you're interested in creating a simple state management system with concepts inspired by Redux Toolkit, you could follow a basic pattern similar to Redux. Here's a minimal example:

// createStore.js
function createStore(reducer, initialState) {
  let state = initialState;
  let listeners = [];

  function getState() {
    return state;
  }

  function dispatch(action) {
    state = reducer(state, action);
    listeners.forEach(listener => listener());
  }

  function subscribe(listener) {
    listeners.push(listener);
    return () => {
      listeners = listeners.filter(l => l !== listener);
    };
  }

  return { getState, dispatch, subscribe };
}

// createSlice.js
function createSlice(options) {
  const { initialState, reducers } = options;

  return (state = initialState, action) => {
    if (reducers.hasOwnProperty(action.type)) {
      return reducers[action.type](state, action);
    }
    return state;
  };
}

// Example usage
const counterSlice = createSlice({
  initialState: { value: 0 },
  reducers: {
    increment: (state) => ({ value: state.value + 1 }),
    decrement: (state) => ({ value: state.value - 1 }),
  },
});

const store = createStore(counterSlice, { value: 0 });

// Subscribe to state changes
const unsubscribe = store.subscribe(() => {
  const state = store.getState();
  console.log('Current state:', state);
});

// Dispatch actions
store.dispatch({ type: 'increment' });
store.dispatch({ type: 'decrement' });

// Unsubscribe when you're done
unsubscribe();
Enter fullscreen mode Exit fullscreen mode

In this example, createStore creates a simple store with getState, dispatch, and subscribe functions. createSlice is used to define a slice of the state with an initial state and reducers.

Please note that this is a very basic example, and real-world state management libraries provide many features for handling asynchronous actions, middleware, and more. If you are working with React, consider using established solutions like Redux or MobX, as they offer more comprehensive tools for state management.

Top comments (0)