Manage states using Redux
Redux is a state managing library used in JavaScript apps. It simply manages the state of your application or in other words, it is used to manage the data of the application. It is used with a library like React. It makes easier to manage state and data. As the complexity of our application increases.
Building Blocks of redux:
Example: In this example we will see the basic implementation of Redux.
Install dependency to use Redux in your application
npm install redux react-redux
Javascript
// index.js import React from "react" ; import ReactDOM from "react-dom" ; import { Provider } from "react-redux" ; import store from "./store" ; import App from "./App" ; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById( "root" ) ); |
Javascript
// App.js import React from 'react' ; import { useSelector, useDispatch } from 'react-redux' ; import { increment, decrement } from './actions' ; function App() { const count = useSelector(state => state.count); const dispatch = useDispatch(); return ( <div> <h1>Counter: {count}</h1> <button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button> </div> ); } export default App; |
Javascript
// store.js import { createStore } from 'redux' ; import counterReducer from './reducers' ; const store = createStore(counterReducer); export default store; |
Javascript
// reducers.js const counterReducer = (state = { count: 0 }, action) => { switch (action.type) { case 'INCREMENT' : return { count: state.count + 1 }; case 'DECREMENT' : return { count: state.count - 1 }; default : return state; } }; export default counterReducer; |
Javascript
// actions.js export const increment = () => { return { type: 'INCREMENT' }; }; export const decrement = () => { return { type: 'DECREMENT' }; }; |
Output:
State Management in React – Hooks, Context API and Redux
While developing a React Application, it is very important to manage the state efficiently for building fully functional applications. As React is growing there are multiple approaches introduced that can help to manage state efficiently depending upon the type of application we are building.
We will discuss the following state management techniques:
Table of Content
- Manage states using Hooks
- Manage states using Context API
- Manage states using Redux
Before we dive deep into state management, let us first understand what is state in React.