Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux connect function explanation

I am new to redux framework. What is App means in the below code. Is it passing Type, Class to connect function? I would like to know how does it work. Apparently connect function returns a new module for export. Can someone point to basic javascript example to understand this code.

export default connect(mapDispatchToProps)(App);
like image 542
muhammad800804 Avatar asked Dec 14 '22 10:12

muhammad800804


2 Answers

The connect() function is an example of a curried function. For JavaScript examples, see this. It's essentially a higher-order function that returns a higher-order component.

The two parts of the connect() function call that may be confusing:

  1. 1st parentheses - these are the arguments the connect function takes - mapDispatchToProps is the 2nd argument out of four optional ones

  2. Between the second set of parentheses is the presentational component (App) that you are seeking to connect to the Redux store via the connect method.

Connect is called with the arguments you pass in. There are essentially two steps since it's a curried function and must be called twice.

The first function call takes the arguments you passed in and returns a higher-order component (a function that takes in a component and returns another):

const enhance = connect(mapDispatchToProps); // 1st call - returns HOC

Next, your App (presentational) component is passed to that higher-order component returned by the 1st call and now stored in enhance

enhance(App); // 2nd call - returns container component

We are 'wrapping' the App component, providing it with all the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.

So, the 2nd call returns a new "connected"/container App component that is connected to the Redux store with all the props/actions injected into it. And that is what gets exported in your snippet. You can read more here: HOC - React Docs

Hope that cleared it up!

like image 56
Joel H Avatar answered Dec 15 '22 23:12

Joel H


In react-redux the connect function itself returns another function, not a plain value. So the syntax you're seeing here is simply function calls, whereby the result of connect(mapDispatchToProps) is a function which is then called with the parameter App. Here's a simple example of a function that returns a function that you can try in a js console.

function makeAdder(x) {
  function adder(y) {
    return x + y;
  }
  // return the inner `adder` function from the `makeAdder` function
  return adder;
}

console.log(makeAdder(5)(4)); // prints 9

like image 26
azundo Avatar answered Dec 15 '22 23:12

azundo