Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class component with Redux

Tags:

reactjs

redux

I am new to React and Redux and as we know, it is best to use class component for those components that have state and the question I would like to ask is that Is it recommended to use functional component for components that have connection and interaction with Redux store since those components that interact with store do not have state locally.

like image 890
Dickens Avatar asked Oct 08 '19 05:10

Dickens


Video Answer


2 Answers

As of version 7.x react-redux now has hooks for functional components

const store = useSelector(store => store)

So that we can use functional component with redux store like class component.

please check below link to get more idea about hooks

https://react-redux.js.org/next/api/hooks

like image 110
niks Avatar answered Sep 23 '22 06:09

niks


It's perfectly fine to connect functional components to redux store.

Functional components don't have a state is not completely correct with hooks. You can add state to functional component with hooks.

Answering your question, you can connect functional component with redux store like below.

import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { Provider, connect } from "react-redux";

const reducers = (state = 0, action) => {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
};

const store = createStore(reducers, 0);

const App = ({ count, handleIncrement, handleDecrement }) => {
  return (
    <div>
      <button onClick={handleIncrement}>+</button>
      <h4>{count}</h4>
      <button onClick={handleDecrement}>-</button>
    </div>
  );
};

const mapStateToProps = state => {
  return { count: state };
};

const mapDispatchToProps = dispatch => {
  return {
    handleIncrement: () => {
      dispatch({ type: "INCREMENT" });
    },
    handleDecrement: () => {
      dispatch({ type: "DECREMENT" });
    }
  };
};

const ConnectedApp = connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

ReactDOM.render(
  <Provider store={store}>
    <ConnectedApp />
  </Provider>,
  document.getElementById("root")
);
like image 29
Nithin Thampi Avatar answered Sep 23 '22 06:09

Nithin Thampi