Use Redux State in React Component
- Now select the state inside your component using hook:
Syntax:
const state = useSelector( ( state ) => state.slice_name.value )
Now to update the state we have to dispatch the actions we defined earlier
const dispatch = useDispatch( )
dispatch(action_name( ) )
Exaplanation:
- Below you can see the two button increment and decrement.
- This button will dispatch the increment and decrement action to the store.
- Reducer inside store will update the value of counter according to the action. Here counter is a state.
- And this state available throughout the application and can be manipulated from any component.
Example:
import './App.css';
import {
useSelector,
useDispatch
} from 'react-redux'
import {
decrement,
increment
} from './store/slices/counterSlice'
function App() {
const count = useSelector((state) => state.counter.value)
const dispatch = useDispatch()
return (
<div className="App">
<header className="App-header">
<p>
Counter {count}
</p>
<button
onClick={() => dispatch(increment())}>
Increment
</button>
<button
onClick={() => dispatch(decrement())}>
Decrement
</button>
</header>
</div>
);
}
export default App;
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './slices/counterSlice'
export const store = configureStore({
reducer: {
counter: counterReducer
},
})
import { createSlice } from '@reduxjs/toolkit'
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
state.value += 1
},
decrement: (state) => {
state.value -= 1
}
},
})
export const { increment, decrement } = counterSlice.actions
export default counterSlice.reducer
import { configureStore } from '@reduxjs/toolkit'
export const store = configureStore({
reducer: {
},
})
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { store } from './store/store'
import { Provider } from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
Start your application using the following command.
npm start
Output:
How to Create Store in React Redux ?
React Redux is a JavaScript library that is used to create and maintain state in React Applications efficiently.
Here React Redux solves the problem by creating a redux store that stores the state and provides methods to use the state inside any component directly or to manipulate the state in a defined manner.
Table of Content
- Redux Toolkit
- How to Build Redux Store and Manage Complex State in ReactJS
- Wrap App with Redux Provider
- Create Redux Store
- Create Redux State Slice Reducer
- Register State Slice in Store
- Use Redux State in React Component
Contact Us