DEV Community

loading...
Cover image for Understand React Redux - Introduction

Understand React Redux - Introduction

Ebraim Carvalho
Front-End Developer | React | JavaScript
・2 min read

This month, I started to learn more about Redux, so I decided to write a basic post with my knowledge of Redux with React. I am also learning, so correct me if there is an error.

For Redux, you need some things:

  • Reducer: A function that manages your actions and return a new state;
  • Actions: A function that tells your reducer what it needs to do;
  • Store: A state that will pass to our application;

There is a recomendation to focus our variables that define our actions, defining a string to a constant.

Let's look at an example, first our Reducer and Actions:

// our constant with a string type
const ADD = 'ADD';

// our action creator, needs to be a pure function
const addMessage = (message) => {
  return {
    type: ADD,
    message: message
  }
}

// our reducer, also needs to be a pure function
const messageReducer = (state = [], action) => {
  switch(action.type) {
    case ADD :
      // join the new message with the others
      return [...state, action.message]
    default :
      return state
  }
}

// need to import {createStore} from 'redux'
const store = createStore(messageReducer)

That's it, our state are ready. Now we need to call it on our component to read the state or send an action. Let's see how we can do that:

import {useState} from 'react';
import { Provider, connect } from "react-redux";

const Presentational = (props) => {
  const [input, setInput] = useState('')

  const handleChange = (e) => {
    setInput(e.target.value)
  }

  const handleSubmit = () => {
    // we can call through the props because we use mapDispatchToProps below
    props.submitNewMessage(input)
    setInput('')
  }

  return (
    <div>
      <h2>Type a new message:</h2>
      <input type="text" value={input} onChange={handleChange} />
      <button onClick={handleSubmit}>Submit new message</button>
      <ul>
        // we can read through the props because we use mapStateToProps below
        {props.messages.map((message, index) => (
          <li key={index}>{message}</li>
        ))}
      </ul>
    </div>
  )
}

const mapStateToProps = (state) => {
  return {messages: state}
};

const mapDispatchToProps = (dispatch) => {
  // if we has another action, we will pass in this object
  return {
    submitNewMessage: (message) => {
      dispatch(addMessage(message))
    }
  }
}

// connect all of this things in a Container wrapper
const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational);

const App = () => {
  return (
    // here the magic happens
    <Provider store={store}>
      <Container />
    </Provider>
  )
}

That's it, I'm learning and that's what I understood so far, what did you think of redux?

Discussion (0)