Home > Web Front-end > JS Tutorial > body text

Modern React with Redux

Linda Hamilton
Release: 2024-10-06 06:21:30
Original
973 people have browsed it

This article focuses on modern React with an emphasis on integrating Redux into React applications for state management. I'll cover some advanced React features like useCallback and useful VS Code extensions to enhance productivity.

Concept Highlights:

  1. mapStateToProps
  2. mapDispatchToProps
  3. Benefits of adding Redux to React
  4. Redux Thunk
  5. Reducers
  6. Selectors
  7. React Snippets in VS Code

1. mapStateToProps

In Redux, mapStateToProps is a function that allows you to map the state from the Redux store to the props of the React component. This allows components to access specific pieces of state.

Syntax:


const mapStateToProps = (state) => {
  return {
    data: state.data,
  },
};


Copy after login

e.g.) In this example, mapStateToProps extracts the count value from the Redux store and makes it available as a prop inside CounterComponent.


const mapStateToProps = (state) => {
  count: state.counter.count,
});

export default connect(mapStateToProps)(CounterComponent);


Copy after login

2. mapDispatchToProps

Similar to mapStateToProps, mapDispatchToProps maps dispatch actions to props, enabling the component to dispatch actions to the Redux store.

Syntax:


const mapDispatchToProps = (dispatch) => {
  return {
    increment: () => dispatch({ type: 'INCREMENT' }),
    decrement: () => dispatch({ type: 'DECREMENT' }),
  },
};


Copy after login

e.g.) In this example, mapDispatchToProps provides incrementCount as a prop to CounterComponent, allowing it to dispatch the increment() action when called.


const mapDispatchToProps = (dispatch) => ({
  incrementCount: () => dispatch(increment()),
});


Copy after login

3. Benefits of Adding Redux to React

Redux can significantly improve your React application, especially as the application grows in complexity. Here are the main benefits:

  • Centralized State Management: Redux provides a single source of truth by managing the state in a centralized store. This makes it easier to manage state changes across the app and improves predictability.

  • State Persistence: Redux makes it easier to save and persist state across page reloads or routes, making the UX smoother.

  • Debugging and Time-Travel Debugging: Redux DevTools allows for advanced debugging and lets you inspect every action and state change, even traveling back to previous states to fix bugs.

  • Separation of Concerns: Redux separates your application's state from your UI, enabling more reusable, maintainable, and testable code.

4. Redux Thunk

Redux Thunk is a middleware that allows to write action creators that return functions instead of action objects. This enables us to perform asynchronous operations (like API calls) within the Redux actions.

Syntax:

 const fetchData = () => {
  return (dispatch) => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => dispatch({ type: 'FETCH_SUCCESS', payload: data }))
      .then(error => dispatch({ type: 'FETCH_ERROR', error }));
  };
};


Copy after login

e.g.) In this example, fetchPosts is an asynchronous action that fetches data from an API and dispatches actions based on the success or failure of the request.


function fetchPosts() {
  return async (dispatch) => {
    dispatch({ type: 'FETCH_POSTS_REQUEST' });
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/posts');
      const posts = await repsosne.json();
      dispatch({ type: 'FETCH_POSTS_SUCCESS', payload: posts });
    } catch (error) {
      dispatch({ type: 'FETCH_POSTS_ERROR', error });
    }
  };
}


Copy after login

5. Reducers

Reducers are pure functions in Redux that take the current state and an action as arguments and return a new state based on the action. Reducers are responsible for updating the state in the Redux store.

Syntax:


const initialState = { count: 0 };

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


Copy after login

e.g.) In this example, the counterReducer handles two actions, INCREMENT and DECREMENT, and updates the count in the state accordingly.


const rootReducer = combineReducers({
  counter: counterReducer,
});

const store = createStore(rootReducer);


Copy after login

6. Selectors

Selectors are functions used to extract or compute derived states from the Redux store. They improve performance by memoizing results and provide a clear API to access parts of the state.

Syntax:


const selectCount = (state) => state.counter.count;


Copy after login

e.g.) In this example, selectUserPosts is a memoized selector that filters posts based on the current user's ID. Selectors can make your code more efficient by avoiding unnecessary recalculations.


const selectUserPosts = createSelector(
  [state => state.posts, state => state.userId],
  (posts, userId) => posts.filter(post => post.userId === userId)
};


Copy after login

7. React Snippets in VS Code

If you're coding in VS Code, installing the React Snippets extension can greatly speed up your workflow. This extension provides handy shortcuts for creating components, hooks, and other common React code structures, helping users write clean and consistent React code more quickly by leveraging code templates.

Modern React with Redux

e.g.) Trying rfc, rafc, or rafce followed by the tab key will generate the following code for a React functional component:


import React from 'react'

const ComponentName = () => {
  return (
    <div>

    </div>
  )
}


Copy after login

The above is the detailed content of Modern React with Redux. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!