Tuesday, March 1, 2022

Redux


Reference:

https://redux.js.org/tutorials/essentials/part-1-overview-concepts

Redux is a pattern and library for managing and updating application state, using events called "actions". It serves as a centralized store for state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable fashion.

Redux is more useful when:

  • You have large amounts of application state that are needed in many places in the app
  • The app state is updated frequently over time
  • The logic to update that state may be complex
  • The app has a medium or large-sized codebase, and might be worked on by many people

Not all apps need Redux.

type and payload in Redux:

Payload is what is keyed ( the key value pairs ) in your actions and passed around between reducers in your redux application. For example -

const someAction = {
  type: "Test",
  payload: {user: "Test User", age: 25},
}

This is a generally accepted convention to have a type and a payload for an action. The payload can be any valid JS type ( array , object, etc ).

Reference:

https://stackoverflow.com/questions/51357412/what-is-a-payload-in-redux-context

 

 

 

super(props) in React



super(props) is a reference to the parents constructor() function, that's all it is. We have to add super(props) every single time we define a constructor() function inside a class-based component.

In JavaScript, super refers to the parent class constructor. (In our example, it points to the React.Component implementation.)

Importantly, you can’t use this in a constructor until after you’ve called the parent constructor. JavaScript won’t let you:

class Checkbox extends React.Component {
  constructor(props) {
    // 🔴 Can’t use `this` yet
    super(props);
    // ✅ Now it’s okay though
    this.state = { isOn: true };
  }
  // ...
}

 

React: connect(mapStateToProps, mapDispatchToProps)



For parent-child communication, simply pass props.

Use state to store the data your current page needs in your controller-view. 

Example

class DummyComponent extends React.Component {
  state = {
    name: 'Manoj'
  }
  render() {
    return <div>Hello {this.state.name}</div>;
  }

Use props to pass data & event handlers down to your child components. 

Example:

class DummyComponent extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }

}

// when using the component
<DummyComponent name="Manoj" />
<DummyComponent name="Ajay" />

 mapStateToProps is used for selecting the part of the data from the store that the connected component needs. The mapStateToProps function should always be written with at least state passed in.

Example:

function mapStateToProps(state) {
return {
a: 42,
todos: state.todos,
filter: state.visibilityFilter,
}
}

// component will receive: props.a, props.todos, and props.filter

 import { connect, Provider } from 'react-redux';
import store from '../../systems/redux/store';

  • By default, a connected component receives props.dispatch and can dispatch actions itself.
  • connect can accept an argument called mapDispatchToProps, which lets you create functions that dispatch when called, and pass those functions as props to your component.
render() {
return <button onClick={() => this.props.toggleTodo(this.props.todoId)} />
}

const mapDispatchToProps = dispatch => {
return {
toggleTodo: todoId => dispatch(toggleTodo(todoId))
}
}

 

react-redux is the library that is passing these methods to your component as props.

dispatch() is the method used to dispatch actions and trigger state changes to the store. react-redux is simply trying to give you convenient access to it.

React Redux includes a <Provider /> component, which makes the Redux store available to the rest of your app:

import React from 'react'
import ReactDOM from 'react-dom'

import { Provider } from 'react-redux'
import store from './store'

import App from './App'

const rootElement = document.getElementById('root')
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
)

 

useSelector reads a value from the store state and subscribes to updates, while useDispatch returns the store's dispatch method to let you dispatch actions.

import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {
decrement,
increment,
incrementByAmount,
incrementAsync,
selectCount,
} from './counterSlice'
import styles from './Counter.module.css'

export function Counter() {
const count = useSelector(selectCount)
const dispatch = useDispatch()

return (
<div>
<div className={styles.row}>
<button
className={styles.button}
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
+
</button>
<span className={styles.value}>{count}</span>
<button
className={styles.button}
aria-label="Decrement value"
onClick={() => dispatch(decrement())}
>
-
</button>
</div>
{/* omit additional rendering output here */}
</div>
)
}

render in React

We have

<body>
  <div id="root"></div>
</body>

In React
import React from 'react';

import { render } from 'react-dom';

class Welcome extends React.Component {
  constructor(props) {
super(props);
}
 
render() { return <h1>Hello, {this.props.name}</h1>; } }
if (document.getElementById('root')) { 
 ReactDOM.render(
   <Welcome name="John" />,
   document.getElementById('root')
 );

}