Redux

Marickian
By -
0
Using Redux in a React Application

Using Redux in a React Application

Introduction

Redux is a predictable state container for JavaScript applications, often used with React for managing application state. Combining Redux with CSS can help create a well-structured, maintainable, and visually appealing web application.

Step 1: Setting Up Your React Application

First, create a new React application using Create React App:

npx create-react-app redux-css-app
cd redux-css-app

Step 2: Installing Redux and React-Redux

Next, install Redux and React-Redux packages:

npm install redux react-redux

Step 3: Setting Up Redux

Create a redux folder in the src directory. Inside the redux folder, create two files: actions.js and reducers.js.

actions.js:

export const increment = () => ({
    type: 'INCREMENT',
});

export const decrement = () => ({
    type: 'DECREMENT',
});

reducers.js:

const initialState = {
    count: 0,
};

const counterReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return { ...state, count: state.count + 1 };
        case 'DECREMENT':
            return { ...state, count: state.count - 1 };
        default:
            return state;
    }
};

export default counterReducer;

Step 4: Creating the Store

Create a store.js file in the redux folder:

import { createStore } from 'redux';
import counterReducer from './reducers';

const store = createStore(counterReducer);

export default store;

Step 5: Connecting Redux to React

Wrap your application with the Provider component from react-redux in the src/index.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import store from './redux/store';

ReactDOM.render(
    
        
    ,
    document.getElementById('root')
);

Step 6: Creating Redux-Connected Components

Create a Counter.js component in the src folder:

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './redux/actions';
import './Counter.css';

const Counter = () => {
    const count = useSelector((state) => state.count);
    const dispatch = useDispatch();

    return (
        

Counter: {count}

); }; export default Counter;

Step 7: Using the Counter Component

Finally, use the Counter component in the App.js file:

import React from 'react';
import Counter from './Counter';

function App() {
    return (
        
); } export default App;

Conclusion

By combining Redux for state management, you can create a well-organized and functional React application. This approach helps keep your code clean and maintainable while providing a great user experience.

Redux documentation

Post a Comment

0Comments

Post a Comment (0)