Getting Started with React and Redux

Prerequisites

Before diving into React and Redux, make sure you have the following installed.

Node.js: You can download and install it from https://nodejs.org/.

Setting Up a React App

To create a new React app, you can use create-react-app a tool that sets up a new React project with a sensible default configuration. Open your terminal and run the following commands.

npx create-react-app my-react-redux-app
cd my-react-redux-app

npm start

Installing Redux

To use Redux in your React app, you need to install the redux and react-redux packages. Run the following command in your project directory.

npm install redux react-redux

Setting Up Redux Store

Create a new file called store.js in your project's src folder. This file will define and configure your Redux store.

// src/store.js
import { createStore } from 'redux';
import rootReducer from './reducers';

const store = createStore(rootReducer);

export default store;

Creating Reducers

Reducers are functions that specify how the application's state changes in response to actions. Create a folder called reducers your src directory and define your reducers. For example.

// src/reducers/index.js


const initialState = {
  // Your initial state here
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    // Handle different actions here
    default:
      return state;
  }
};

export default rootReducer;

Connecting React with Redux

Now that you have your store and reducers set up, you can connect your React components with Redux. Use the Provider component from react-redux to make the Redux store available to the entire app.

// src/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')
);

Dispatching Actions

In your React components, you can use the useDispatch hook to dispatch actions to the Redux store. For example.

// src/components/MyComponent.js
import React from 'react';
import { useDispatch } from 'react-redux';

const MyComponent = () => {
  const dispatch = useDispatch();

  const handleClick = () => {
    dispatch({ type: 'INCREMENT' }); // Dispatch an action
  };

  return (
    <div>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};

export default MyComponent;

Accessing State

To access the Redux state in your components, you can use the useSelector hook. For example.

// src/components/AnotherComponent.js
import React from 'react';
import { useSelector } from 'react-redux';

const AnotherComponent = () => {
  const count = useSelector((state) => state.count); // Access state property

  return (
    <div>
      <p>Count: {count}</p>
    </div>
  );
};

export default AnotherComponent;