React – How to manage state by Redux (2)?

Redux Toolkit

Setup

  • Install packages
yarn add react-redux
yarn add @reduxjs/toolkit
  • Create Slice API
// src/state/slice.js

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  appVersion: '0.0.0'
}

export const appSlice = createSlice({
  name: 'root',  // state name
  initialState, // app state
  reducers: {   // reducers
    storeAppVersion: (state, action) => { // actions
      state.appVersion = action.payload
    },
  },
})

// Export state name
export const { name } = appSlice

// Export actions
export const {
  storeAppVersion
} = appSlice.actions

// Export reducers
export default appSlice.reducer
  • Create redux store
// src/state/store.js

import { configureStore } from '@reduxjs/toolkit'
import appReducer from './slice'

const store = configureStore({
  reducer: {
    'root': appReducer, // 'root' is state name defined in slice
    // ...
  },
})

export default store
// App.js

import React from 'react'
import Home from './src/screens/Home'
import { Provider } from 'react-redux'
import store from './src/state/store'

export default function App() {
  return (
    <Provider store={store}><Home /></Provider>
  )
}
  • Get/ set state from/ to store
import React from 'react'

import { useSelector, useDispatch } from 'react-redux'
import { name, storeAppVersion } from '../../state/slice'

export default function Home() {

  /** State test */
  // GET current state
  const savedVersion = useSelector((state) => state[name].appVersion)

  // SET new verison
  const dispatch = useDispatch()
  dispatch(storeAppVersion('1.0.0'))

...

}

Be the first to comment

Leave a Reply

Your email address will not be published.


*