Skip to content

Instantly share code, notes, and snippets.

@kaineer
Last active February 12, 2025 07:45
Show Gist options
  • Select an option

  • Save kaineer/067afeb8ab205b56a3075b7120b5c938 to your computer and use it in GitHub Desktop.

Select an option

Save kaineer/067afeb8ab205b56a3075b7120b5c938 to your computer and use it in GitHub Desktop.

Ставим redux toolkit

$ npm install -SE react-redux @reduxjs/toolkit

Создаем слайс, который будет хранить состояние

// src/slices/color.js
import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  color: ''
};

export const ColorSlice = createSlice({
  name: 'color',
  initialState,
  reducers: {
    setColor: (state, action) => {
      state.color = action.payload;
    }
  },
  selectors: {
    getColor: (state) => state.color,
  }
});

export const ColorReducer = ColorSlice.reducer;
export const {
  getColor
} = ColorSlice.selectors;

Создаем центральное хранилище

// src/store/index.js
import { combineReducers, configureStore }
  from '@reduxjs/toolkit';

import { ColorSlice } from '../slices/color'

const reducer = combineReducers({
  [ColorSlice.reducerPath]: ColorSlice.reducer,
});

export const store = configureStore({
  reducer,
})

Подключаем его в приложение

// src/App.jsx
// ...

import { store } from './store/index'

const App = () => {
  return (
    <BrowserRouter>
      <Provider store={store}>
        ...
      </Provider>
    </BrowserRouter>
  )
}

Теперь мы можем сохранять состояние в store и читать оттуда

// src/pages/page2.jsx
import { ColorSlice, getColor } from '../slices/color'
import { useSelector,  useDispatch } from 'react-redux'

export const Page2 = () => {
  const color = useSelector(getColor);
  const { setColor } = ColorSlice.actions;
  const dispatch = useDispatch();
  const updateColor = (value) => {
    dispatch(setColor(value))
  };

  return (
    <>
      <Semaphore color={color} setColor={updateColor} />
    </>
  )
}

Понятное дело, придется убрать собственное состояние из переключателя

// src/.../Semaphore.jsx
export const Semaphore = ({ color, setColor }) => {
  return (
    <>
      <NameInput color={color} setColor={setColor} />
    </>
  )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment