38
loading...
This website collects cookies to deliver better user experience
npm install @reduxjs/toolkit react-redux
// src/redux/store.js
import { configureStore } from '@reduxjs/toolkit'
export const store = configureStore({
reducer: {},
})
// src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { store } from './redux/store' // import your store
import { Provider } from 'react-redux' // import the provider
ReactDOM.render(
<Provider store={store}> // place provider around app, pass store as prop
<App />
</Provider>,
document.getElementById('root')
)
// src/redux/PostSlice.js
import { createSlice } from '@reduxjs/toolkit'
function addPost(text) {
return {
type: 'ADD_POST',
payload: { text },
}
}
const addPost = createAction('ADD_POST')
addPost({ text: 'Hello World' })
const actionCreator = createAction('SOME_ACTION_TYPE')
console.log(actionCreator.toString())
// "SOME_ACTION_TYPE"
console.log(actionCreator.type)
// "SOME_ACTION_TYPE"
const reducer = createReducer({}, (builder) => {
// actionCreator.toString() will automatically be called here
// also, if you use TypeScript, the action type will be correctly inferred
builder.addCase(actionCreator, (state, action) => {})
// Or, you can reference the .type field:
// if using TypeScript, the action type cannot be inferred that way
builder.addCase(actionCreator.type, (state, action) => {})
})
// src/redux/PostSlice.js
const CREATE_POST = 'CREATE_POST'
export function addPost(id, title) {
return {
type: CREATE_POST,
payload: { id, title },
}
}
const initialState = []
export default function postsReducer(state = initialState, action) {
switch (action.type) {
case CREATE_POST: {
// Your code
break
}
default:
return state
}
}
// src/redux/PostSlice.js
import { createSlice } from '@reduxjs/toolkit'
const postsSlice = createSlice({
name: 'posts',
initialState: [],
reducers: {
createPost(state, action) {}
},
})
const { createPost } = postsSlice.actions
export const { createPost } = actions
export default PostSlice.reducer
Redux action types are not meant to be exclusive to a single slice.
JS modules can have "circular reference" problems if two modules try to import each other.
// src/redux/store.js
import { configureStore } from '@reduxjs/toolkit'
import postsReducer from './postSlice'
const rootReducer = combineReducers({
posts: postsReducer
})
const rootReducer = combineReducers({
users: usersReducer,
posts: postsReducer
})
"Own" a piece of state, including what the initial value is.
Define how that state is updated.
Define which specific actions result in state updates