Skip to content

Instantly share code, notes, and snippets.

@ihollander
Created March 11, 2021 12:15
Show Gist options
  • Save ihollander/a12f74c47b24e6596f6c8d79a0c472ea to your computer and use it in GitHub Desktop.
Save ihollander/a12f74c47b24e6596f6c8d79a0c472ea to your computer and use it in GitHub Desktop.
React Redux Basic Setup

React Redux Basic Setup

Working example of the code below

Install dependencies:

npm install @reduxjs/toolkit react-redux

Create a reducer with createSlice:

// ./src/redux/counterSlice.js
import { createSlice } from "@reduxjs/toolkit";

const slice = createSlice({
  name: "counter",
  initialState: {
    value: 0
  },
  reducers: {
    increment(state) {
      state.value += 1;
    },
    decrementBy(state, action) {
      state.value -= action.payload;
    }
  }
});

// reducer function export
export default slice.reducer;

// action creator exports
export const { increment, decrementBy } = slice.actions;

Create the Redux store with configureStore:

// ./src/redux/store.js
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";

const store = configureStore({
  reducer: {
    counter: counterReducer
  }
});

export default store;

Connect the store to React using the Provider:

// ./src/index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from "./redux/store";
import App from "./components/App";

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

Use the useSelector hook to access data from the store:

// ./src/components/App
import { useSelector } from "react-redux";
import UpdateCount from "./UpdateCount"

export default function App() {
  // state is ALL the state in the Redux store
  // in the store, each reducer will have its own key on state (state.counter === state from our counterSlice reducer)
  // then you can access any state from that reducer
  const count = useSelector((state) => state.counter.value);

  return (
    <div>
      <h1>Count: {count}</h1>
      <UpdateCount />
    </div>
  );
}

Use the useDispatch hook to dispatch actions to update state

// ./src/components/UpdateCount
import { useDispatch } from "react-redux";
import { increment, decrementBy } from "../redux/counterSlice";

export default function UpdateCount() {
  const dispatch = useDispatch();

  function handleAdd() {
    const action = increment(); // { type: "counter/increment" }
    dispatch(action);
  }

  function handleSubtract() {
    const action = decrementBy(10); // { type: "counter/decrementBy", payload: 10 }
    dispatch(action);
  }

  return (
    <div>
      <button onClick={handleAdd}>Add</button>
      <button onClick={handleSubtract}>Subtract</button>
    </div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment