State updates may be asynchronous, what is exactly this.props? - javascript

state = {
persons:[
{id:"cbhc", name:"surya",age:26,sex:"male"},
{id:"rgt", name:"sachin",age:36,sex:"male"},
{id:"cbcchc", name:"rahul",age:46,sex:"male"}
],
showdetails:false,
**counter:0**,
};
The above was the state of data in my application:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
What was exactly here: props.increment ????
My piece of code:
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
I want to know what is props.increment ??
my skeleton of component:
import React from "react";
//import mystyles from "./person.module.css";
//import Studentoutput from "./cockpit/cockpit";
const Singlestudent = props => {
console.log("child component skeleton rendering...");
return (
<div>
<p onClick={props.click}>{props.name}</p>
<p>{props.age}</p>
<p>{props.id}</p>
**<p>{props.increment}</p>**
<input type="text" onChange={props.update} value={props.name} />
</div>
);
};
export default Singlestudent;
since my state data is embedded inside with nested array and object, using map method to structure my skeleton comp data as below:
// import React from "react";
// //import mystyles from "./person.module.css";
// const Studentoutput = props => <input type="text" value={props.name} />;
// export default Studentoutput;
import React from "react";
import Singlestudent from "./student/singlestudent";
const Studentinfo = props => {
console.log("child component details rendering...");
return props.details.map((studentinfo, index) => {
return (
<Singlestudent
key={studentinfo.id}
name={studentinfo.name}
age={studentinfo.age}
**increment={props.increment}**
update={props.updated(studentinfo.id)}
click={props.clicked(studentinfo.id)}
/>
);
});
};
export default Studentinfo;
i passed increment={1} , hardcoded it.
now finally passing the above to my main parent which renders on browser
return (
<div className={mystyles.parent}>
<Studentinfo
details={this.state.details}
updated={this.updateStudentHandler}
clicked={this.deleteStudentHandler}
**increment={1}**
/>
</div>
);
from the above code snippet i'm changing my counter value through updateStudentHandler
updateStudentHandler = id => event => {
//debugger;
const studentIndex = this.state.details.findIndex(d => d.id === id);
console.log(studentIndex);
let duplicate = {
...this.state.details[studentIndex]
};
duplicate.name = event.target.value;
const dd = [...this.state.details];
dd[studentIndex] = duplicate;
this.setState({
details: dd
});
this.setState((referencetoprevState, Props) => {
return {
counter: referencetoprevState.counter + Props.increment
};
});
};
as soon as i change the text in input box, my counter should update but it returns NaN, why ????
refer to below screenshot attached
output of counter variable
but if i change the below code
this.setState((state, props) => {
return { counter: state.counter + props.increment };
});
with a value (9000) instead of props.increment results in updating the counter value as expected.
this.setState((state, props) => {
return { counter: state.counter + 9000 };
});
why i need to provide explicitly value not just like props.increment similar to state.counter because state.counter is taking its value as 0 from the previous state but props.increment not taking the value 1 from increment={1} from jsx of user defined component which is Studentinfo comp ??
Any limitations/reasons ??

As the React documentation states:
When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object “props”.
I suggest to read further the official docs, especially Rendering a Component part.
Additionally setState() one here explains further:
this.setState((state, props) => {
return {counter: state.counter + props.step};
});
Both state and props received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with state.
In summary:
Basically you are using setState() function's updater argument in your code which takes two parameters, state and props:
state: is a reference to the component's state - mentioned above - at the time the change is being applied aka previous state.
props: current properties of the component.
You can think of like having the previous state and current properties of the component in two different arguments.
I hope this helps!

Yes i got , just like setting values to an object inside state, we provide values to props in the element tag which is jsx, so from my above code i figured out few things.
As per my understanding i believe that updater function for setState has two params, which basically sits in order as the first param would be previous state and the second is the current property of component.
Here my main component which renders on page with all other child components is .
so, props.increment is coming from Appl which extends Component from "react".
removing increment prop from my skeleton and body of skeleton i.e, from Singlestudent and Studentinfo comps
so finally :
this.setState((referencetoprevState, Props) => {
return {
counter: referencetoprevState.counter + Props.increment
};
});
would be:
this.setState((referencetoprevState, Props) => {
return {
counter: referencetoprevState.counter + 1
};
});

Related

How to trigger useEffects before render in React?

I have a prop being passed from a parent component to a child component which changes based on the user's input.
I want to trigger a data fetch in the child component when that prop changes before the child component is rendered. How can I do it?
I tried in the following manner by using useEffects(()=>{},[props.a, props.b]) but that is always called after the render. Please help!
import React, { useEffect, useState } from "react";
import "./styles.css";
export default function parentComponent() {
const [inputs, setInputs] = useState({ a: "", b: "" });
return (
<>
<input
value={inputs.a}
onChange={(event) => {
const value = event.target.value;
setInputs((prevState) => {
return { ...prevState, a: value };
});
}}
/>
<input
value={inputs.b}
onChange={(event) => {
const value = event.target.value;
setInputs((prevState) => {
return { ...prevState, b: value };
});
}}
/>
<ChildComponent a={inputs.a} b={inputs.b} />
</>
);
}
function ChildComponent(props) {
const [isLoading, setIsLoading] = useState(true);
const [data, setData] = useState({});
useEffect(() => {
console.log("updating new data based on props.a: " + props.a);
setData({ name: "john " + props.a });
return () => {};
}, [props.a, props.b]);
useEffect(() => {
console.log("data successfully changed");
console.log(data);
if (Object.keys(data).length !== 0) {
setIsLoading(false);
}
return () => {};
}, [data]);
function renderPartOfComponent() {
console.log("rendering POC with props.a: " + props.a);
return <div>data is: {data.name}</div>;
}
return (
<div className="App">{isLoading ? null : renderPartOfComponent()}</div>
);
}
In the console what I get is:
rendering POC with props.a: fe
rendering POC with props.a: fe
updating new data based on props.a: fe
rendering POC with props.a: fe
rendering POC with props.a: fe
data successfully changed
Object {name: "john fe"}
rendering POC with props.a: fe
rendering POC with props.a: fe
If you know how I can make the code more efficient, that would be a great help as well!
Here's the codesandbox link for the code: https://codesandbox.io/s/determined-northcutt-6z9f8?file=/src/App.js:0-1466
Solution
You can use useMemo, which doesn't wait for a re-render. It will execute as long as the dependencies are changed.
useMemo(()=>{
doSomething() //Doesn't want until render is completed
}, [dep1, dep2])
You can use function below:
// utils.js
const useBeforeRender = (callback, deps) => {
const [isRun, setIsRun] = useState(false);
if (!isRun) {
callback();
setIsRun(true);
}
useEffect(() => () => setIsRun(false), deps);
};
// yourComponent.js
useBeforeRender(() => someFunc(), []);
useEffect is always called after the render phase of the component. This is to avoid any side-effects from happening during the render commit phase (as it'd cause the component to become highly inconsistent and keep trying to render itself).
Your ParentComponent consists of Input, Input & ChildComponent.
As you type in textbox, ParentComponent: inputs state is modified.
This state change causes ChildComponent to re-render, hence renderPartOfComponent is called (as isLoading remains false from previous render).
After re-render, useEffect will be invoked (Parent's state propagates to Child).
Since isLoading state is modified from the effects, another rendering happens.
I found the solution by creating and maintaining state within the ChildComponent
So, the order of processes was this:
props modified -> render takes place -> useEffect block is executed.
I found the workaround by simply instantiating a state within the childComponent and making sure that the props state is the same as the one in the child component before rendering, else it would just show loading... This works perfectly.
Nowadays you can use useLayoutEffect which is a version of useEffect that fires before the browser repaints the screen.
Docs: https://beta.reactjs.org/reference/react/useLayoutEffect

React component props don't get updated with redux store

Button.js component
import React from "react"
import "../styles/button.scss"
import store from "../index"
class Button extends React.Component {
constructor(props) {
super(props)
this.buttonTextChanger()
}
buttonTextChanger() {
this.buttonText = "MainPage" === this.props.state.page ? "Az adatokhoz" : "A főoldalra"
}
logger = (actualPage) => {
this.props.onButtonClick(actualPage)
console.log("state from store before textchange", store.getState())
console.log("state from props before textchange", this.props.state)
this.buttonTextChanger()
}
render() {
return (
<div id="container">
<button className="learn-more" onClick = {() => this.logger(this.props.state.page)}>
<span className="circle" aria-hidden="true">
<span className="icon arrow"></span>
</span>
<span className="button-text">{this.buttonText}</span>
</button>
</div>
)
}
}
export default Button
My problem is that the component's props don't seem to be updated with the redux store. The redux store updates to the correct value after the onClick function runs, mapStateToProps also runs with the correct state and still after these if I try to log the state from the prop I get the old value. If I do the same log in the render function before returning the JSX I get the correct state from props and I can't get my head around why it isn't updated immediately after the redux store is.
So if I modify the code to the following it works as expected:
logger = (actualPage) => {
this.props.onButtonClick(actualPage)
console.log("state from store before textchange", store.getState())
}
render() {
console.log("state from props before textchange", this.props.state)
this.buttonTextChanger()
return (
<div id="container">
<button className="learn-more" onClick = {() => this.logger(this.props.state.page)}>
<span className="circle" aria-hidden="true">
<span className="icon arrow"></span>
</span>
<span className="button-text">{this.buttonText}</span>
</button>
</div>
)
}
}
Reducer function
import { combineReducers } from "redux"
export const changePageReducer = (state = {page : "MainPage"}, action) => {
if (action.type === "CHANGE_PAGE")
if (action.payload !== state.page) {
return action.payload
}
return state.page
}
export const combinedReducers = combineReducers({page : changePageReducer})
Button container
import { connect } from "react-redux"
import Button from "../components/Button"
import changePage from "../actions/changePage"
const mapStateToProps = (state) => {
console.log("az injectelt state", state)
return {state}
}
const mapDispatchToProps = (dispatch) => {
return {
onButtonClick : (page) => {
switch (page) {
case "MainPage":
dispatch(changePage("DataPage"))
break
case "DataPage":
dispatch(changePage("MainPage"))
break
default:
dispatch(changePage("MainPage"))
}
}
}
}
const ChangePageContainer = connect(mapStateToProps, mapDispatchToProps)(Button)
export default ChangePageContainer
But I'd like to extract the buttonTextChanger() function call from the render function and call it on click.
TLDR:
the problem:
logger = (actualPage) => {
console.log("prop state value before dispatch", this.props.state)
console.log("store value before dispatch", store.getState())
this.props.onButtonClick(actualPage)
console.log("prop state value after dispatch", this.props.state)
console.log("store value after dispatch", store.getState())
}
also there is a console.log in the mapStateToProps function to see the state that gets passed to props.
This yields:
prop state value before dispatch {page: "MainPage"}
store value before dispatch {page: "MainPage"}
state when mapStateToProps function called {page: "DataPage"}
store value after dispatch {page: "DataPage"}
prop state value after dispatch {page: "MainPage"}
So the prop doesn't get updated.
So, you can't wrap your head around why this.props.state isn't updated even after calling the dispatcher?
You see,
Redux is entirely built on functional programming, and now with hooks, React is also fully moving towards Functional Programming, hell even JavaScript was originally built as Functional Programming.
One thing that's entirely different from OOP and the coolest thing too is that, There are no mutations in Functional Programming. There isn't. Vanilla Redux is fully FP having only pure functions - functions without side effects. That's why you need Redux Saga or other library for making API calls - unpure functions.
Cutting to the chase,
logger = (actualPage) => {
// here,
// actualPage => new value
// this.props.state => old value
// they will remain as such throughout this function
console.log("prop state value before dispatch", this.props.state)
console.log("store value before dispatch", store.getState())
this.props.onButtonClick(actualPage)
// even if you update the Redux Store,
// `this.props.state` will still have the old value
// since this value will not be mutated
console.log("prop state value after dispatch", this.props.state)
console.log("store value after dispatch", store.getState())
}
Then what about store.getState(), their values are updated, you may ask.
Notice how it's not store.getState but instead store.getState()? Yes it is a function instead of a value. Whenever you call them, they return the latest value and there isn't any mutations in them. In your case, the second time you are calling after dispatching the action, hence you get the latest value. It's not mutation, store.getState() just grabbed the latest value there is and returned it to you. logger() will get the new values once that first call is over, then the cycle repeats again.
Action dispatchers will create a new state from the old state, that's why you can time travel in Redux DevTools.
Again recapping
logger = (actualPage) => {
// old value
console.log("prop state value before dispatch", this.props.state)
// old value
console.log("store value before dispatch", store.getState())
// new value
this.props.onButtonClick(actualPage)
// redux would be updated with new values by now
// but still old value - no mutation
console.log("prop state value after dispatch", this.props.state)
// new value
console.log("store value after dispatch", store.getState())
}

Updating and merging state object using React useState() hook

I'm finding these two pieces of the React Hooks docs a little confusing. Which one is the best practice for updating a state object using the state hook?
Imagine a want to make the following state update:
INITIAL_STATE = {
propA: true,
propB: true
}
stateAfter = {
propA: true,
propB: false // Changing this property
}
OPTION 1
From the Using the React Hook article, we get that this is possible:
const [count, setCount] = useState(0);
setCount(count + 1);
So I could do:
const [myState, setMyState] = useState(INITIAL_STATE);
And then:
setMyState({
...myState,
propB: false
});
OPTION 2
And from the Hooks Reference we get that:
Unlike the setState method found in class components, useState does
not automatically merge update objects. You can replicate this
behavior by combining the function updater form with object spread
syntax:
setState(prevState => {
// Object.assign would also work
return {...prevState, ...updatedValues};
});
As far as I know, both works. So, what is the difference? Which one is the best practice? Should I use pass the function (OPTION 2) to access the previous state, or should I simply access the current state with spread syntax (OPTION 1)?
Both options are valid, but just as with setState in a class component you need to be careful when updating state derived from something that already is in state.
If you e.g. update a count twice in a row, it will not work as expected if you don't use the function version of updating the state.
const { useState } = React;
function App() {
const [count, setCount] = useState(0);
function brokenIncrement() {
setCount(count + 1);
setCount(count + 1);
}
function increment() {
setCount(count => count + 1);
setCount(count => count + 1);
}
return (
<div>
<div>{count}</div>
<button onClick={brokenIncrement}>Broken increment</button>
<button onClick={increment}>Increment</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>
If anyone is searching for useState() hooks update for object
Through Input
const [state, setState] = useState({ fName: "", lName: "" });
const handleChange = e => {
const { name, value } = e.target;
setState(prevState => ({
...prevState,
[name]: value
}));
};
<input
value={state.fName}
type="text"
onChange={handleChange}
name="fName"
/>
<input
value={state.lName}
type="text"
onChange={handleChange}
name="lName"
/>
Through onSubmit or button click
setState(prevState => ({
...prevState,
fName: 'your updated value here'
}));
The best practice is to use separate calls:
const [a, setA] = useState(true);
const [b, setB] = useState(true);
Option 1 might lead to more bugs because such code often end up inside a closure which has an outdated value of myState.
Option 2 should be used when the new state is based on the old one:
setCount(count => count + 1);
For complex state structure consider using useReducer
For complex structures that share some shape and logic you can create a custom hook:
function useField(defaultValue) {
const [value, setValue] = useState(defaultValue);
const [dirty, setDirty] = useState(false);
const [touched, setTouched] = useState(false);
function handleChange(e) {
setValue(e.target.value);
setTouched(true);
}
return {
value, setValue,
dirty, setDirty,
touched, setTouched,
handleChange
}
}
function MyComponent() {
const username = useField('some username');
const email = useField('some#mail.com');
return <input name="username" value={username.value} onChange={username.handleChange}/>;
}
Which one is the best practice for updating a state object using the state hook?
They are both valid as other answers have pointed out.
what is the difference?
It seems like the confusion is due to "Unlike the setState method found in class components, useState does not automatically merge update objects", especially the "merge" part.
Let's compare this.setState & useState
class SetStateApp extends React.Component {
state = {
propA: true,
propB: true
};
toggle = e => {
const { name } = e.target;
this.setState(
prevState => ({
[name]: !prevState[name]
}),
() => console.log(`this.state`, this.state)
);
};
...
}
function HooksApp() {
const INITIAL_STATE = { propA: true, propB: true };
const [myState, setMyState] = React.useState(INITIAL_STATE);
const { propA, propB } = myState;
function toggle(e) {
const { name } = e.target;
setMyState({ [name]: !myState[name] });
}
...
}
Both of them toggles propA/B in toggle handler.
And they both update just one prop passed as e.target.name.
Check out the difference it makes when you update just one property in setMyState.
Following demo shows that clicking on propA throws an error(which occurs setMyState only),
You can following along
Warning: A component is changing a controlled input of type checkbox to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
It's because when you click on propA checkbox, propB value is dropped and only propA value is toggled thus making propB's checked value as undefined making the checkbox uncontrolled.
And the this.setState updates only one property at a time but it merges other property thus the checkboxes stay controlled.
I dug thru the source code and the behavior is due to useState calling useReducer
Internally, useState calls useReducer, which returns whatever state a reducer returns.
https://github.com/facebook/react/blob/2b93d686e3/packages/react-reconciler/src/ReactFiberHooks.js#L1230
useState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
currentHookNameInDev = 'useState';
...
try {
return updateState(initialState);
} finally {
...
}
},
where updateState is the internal implementation for useReducer.
function updateState<S>(
initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
return updateReducer(basicStateReducer, (initialState: any));
}
useReducer<S, I, A>(
reducer: (S, A) => S,
initialArg: I,
init?: I => S,
): [S, Dispatch<A>] {
currentHookNameInDev = 'useReducer';
updateHookTypesDev();
const prevDispatcher = ReactCurrentDispatcher.current;
ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher.current = prevDispatcher;
}
},
If you are familiar with Redux, you normally return a new object by spreading over previous state as you did in option 1.
setMyState({
...myState,
propB: false
});
So if you set just one property, other properties are not merged.
One or more options regarding state type can be suitable depending on your usecase
Generally you could follow the following rules to decide the sort of state that you want
First: Are the individual states related
If the individual state that you have in your application are related to one other then you can choose to group them together in an object. Else its better to keep them separate and use multiple useState so that when dealing with specific handlers you are only updating the relavant state property and are not concerned about the others
For instance, user properties such as name, email are related and you can group them together Whereas for maintaining multiple counters you can make use of multiple useState hooks
Second: Is the logic to update state complex and depends on the handler or user interaction
In the above case its better to make use of useReducer for state definition. Such kind of scenario is very common when you are trying to create for example and todo app where you want to update, create and delete elements on different interactions
Should I use pass the function (OPTION 2) to access the previous
state, or should I simply access the current state with spread syntax
(OPTION 1)?
state updates using hooks are also batched and hence whenever you want to update state based on previous one its better to use the callback pattern.
The callback pattern to update state also comes in handy when the setter doesn't receive updated value from enclosed closure due to it being defined only once. An example of such as case if the useEffect being called only on initial render when adds a listener that updates state on an event.
Both are perfectly fine for that use case. The functional argument that you pass to setState is only really useful when you want to conditionally set the state by diffing the previous state (I mean you can just do it with logic surrounding the call to setState but I think it looks cleaner in the function) or if you set state in a closure that doesn't have immediate access to the freshest version of previous state.
An example being something like an event listener that is only bound once (for whatever reason) on mount to the window. E.g.
useEffect(function() {
window.addEventListener("click", handleClick)
}, [])
function handleClick() {
setState(prevState => ({...prevState, new: true }))
}
If handleClick was only setting the state using option 1, it would look like setState({...prevState, new: true }). However, this would likely introduce a bug because prevState would only capture the state on initial render and not from any updates. The function argument passed to setState would always have access to the most recent iteration of your state.
Both options are valid but they do make a difference.
Use Option 1 (setCount(count + 1)) if
Property doesn't matter visually when it updates browser
Sacrifice refresh rate for performance
Updating input state based on event (ie event.target.value); if you use Option 2, it will set event to null due to performance reasons unless you have event.persist() - Refer to event pooling.
Use Option 2 (setCount(c => c + 1)) if
Property does matter when it updates on the browser
Sacrifice performance for better refresh rate
I noticed this issue when some Alerts with autoclose feature that should close sequentially closed in batches.
Note: I don't have stats proving the difference in performance but its based on a React conference on React 16 performance optimizations.
I find it very convenient to use useReducer hook for managing complex state, instead of useState. You initialize state and updating function like this:
const initialState = { name: "Bob", occupation: "builder" };
const [state, updateState] = useReducer(
(state, updates) => {...state, ...updates},
initialState
);
And then you're able to update your state by only passing partial updates:
updateState({ occupation: "postman" })
The solution I am going to propose is much simpler and easier to not mess up than the ones above, and has the same usage as the useState API.
Use the npm package use-merge-state (here). Add it to your dependencies, then, use it like:
const useMergeState = require("use-merge-state") // Import
const [state, setState] = useMergeState(initial_state, {merge: true}) // Declare
setState(new_state) // Just like you set a new state with 'useState'
Hope this helps everyone. :)

Mutating nested object/arrays as states in React [duplicate]

This question already has answers here:
Whats the best way to update an object in an array in ReactJS?
(4 answers)
Closed 4 years ago.
I am using React components which look like this (a simplified version of the components I used, below).
My question is: how to make the same but using this.setState?
The below code works, but I am mutating the state directly, and I am receiving the following warning:
Do not mutate state directly. Use setState()
class App extends Component {
constructor(props) {
super(props);
this.state = {
playerState: [
{
name: 'Jack',
hp: 30
},{
name: 'Alan',
hp: 28
}
],
};
}
lowerPlayerHealth = (index) => () => {
this.state.playerState[index].hp = this.state.playerState[index].hp - 1
this.forceUpdate();
}
render() {
return (
<div className="App">
<p>Player 1: {this.state.playerState[0].name}</p>
<p>Health: {this.state.playerState[0].hp}</p>
<button onClick={this.lowerPlayerHealth(0)}>Hit player 1</button>
<p>Player 2: {this.state.playerState[1].name}</p>
<p>Health: {this.state.playerState[1].hp}</p>
<button onClick={this.lowerPlayerHealth(1)}>Hit player 2</button>
</div>
);
}
}
When rendered, it looks like this:
If you want to modify an existing value in the state, you should never get the value directly from the state and update the state object, but rather use the updater function in setState so you can guarantee the state values are the ones you need at the time of updating the state. This is just how React's state works and it's a very common React mistake.
From the official docs
setState() does not always immediately update the component. It may
batch or defer the update until later. This makes reading this.state
right after calling setState() a potential pitfall. Instead, use
componentDidUpdate or a setState callback (setState(updater,
callback)), either of which are guaranteed to fire after the update
has been applied. If you need to set the state based on the previous
state, read about the updater argument below.
setState() will always lead to a re-render unless
shouldComponentUpdate() returns false. If mutable objects are being
used and conditional rendering logic cannot be implemented in
shouldComponentUpdate(), calling setState() only when the new state
differs from the previous state will avoid unnecessary re-renders.
The first argument is an updater function with the signature:
(state, props) => stateChange
state is a reference to the component state at the time the change is
being applied. It should not be directly mutated. Instead, changes
should be represented by building a new object based on the input from
state and props.
Both state and props received by the updater function are guaranteed
to be up-to-date. The output of the updater is shallowly merged with
state.
So you must get the value exactly when you want to update the component inside the setState function using the first argument of the updater function.
lowerPlayerHealth = (index) => () => {
// use setState rather than mutating the state directly
this.setState((state, props) => {
// state here is the current state. Use it to update the current value found in state and ensure that it will be set correctly
return (state); // update state ensuring the correct values
});
}
Solution
To lower a value found in state:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
playerState: [
{
name: 'Jack',
hp: 30
}, {
name: 'Alan',
hp: 28
}
],
};
}
lowerPlayerHealth = (index) => () => {
this.setState((state, props) => {
state.playerState[index].hp -=1; //update the current value found in state
return (state); // update state ensuring the correct values
});
}
render() {
return (
<div className="App">
<p>Player 1: {this.state.playerState[0].name}</p>
<p>Health: {this.state.playerState[0].hp}</p>
<button onClick={this.lowerPlayerHealth(0)}>Hit player 1</button>
<p>Player 2: {this.state.playerState[1].name}</p>
<p>Health: {this.state.playerState[1].hp}</p>
<button onClick={this.lowerPlayerHealth(1)}>Hit player 2</button>
</div>
);
}
}
You've answered your own question: don't mutate state. Also, best practice suggests using the function version of setState.
Since playerState is an array, use Array.map to create a new array containing the same objects, replacing only the one you want to change:
lowerPlayerHealth = (indexToUpdate) => () => {
this.setState(state => ({
...state,
playerState: state.playerState.map(
(item, index) => index === indexToUpdate
? {
...item,
hp: item.hp - 1
}
: oldItem
)
}));
}
If you made playerState an object instead of an array, you can make it tidier:
lowerPlayerHealth = (indexToUpdate) => () => {
this.setState(state => ({
...state,
playerState: {
...state.playerState,
[indexToUpdate]: {
...state.playerState[indexToUpdate],
hp: state.playerState[idToindexToUpdatepdate].hp - 1
}
}
}));
}

How does reselect affect rendering of components

I don't really understand how does reselect reduces component's rendering. This is what I have without reselect:
const getListOfSomething = (state) => (
state.first.list[state.second.activeRecord]
);
const mapStateToProps = (state, ownProps) => {
console.log(state.first.list, state.second.activeRecord);
return {
...ownProps,
listOfSomething: getListOfSomething(state)
}
};
It compounds an element from some list based on some value. Render is called each time anything in the state changes, so for example my console.log outputs:
{}, ""
{}, ""
{}, ""
{}, "1"
{"filled", "1"}
because something is going on in the different part of store. Thus the component is rendered 5 times, 2 redundantly.
Using reselect however:
const getList = state => state.first.list;
const getActiveRecord = state => state.second.activeRecord;
const listOfSomething = (list, activeRecord) => {
console.log(list, activeRecord);
return list[activeRecord];
}
const getListOfSomething = createSelector(getList, getActiveRecord, listOfSomething);
const mapStateToProps = (state, ownProps) => {
console.log(state.first.list, state.second.activeRecord);
return {
...ownProps,
listOfSomething: getListOfSomething(state)
}
};
Here my first selector console.log outputs:
{}, ""
{}, "1"
{"filled", "1"}
The second:
{}, ""
{}, ""
{}, ""
{}, "1"
{"filled", "1"}
And the component is rendered properly - 3 times !
Why is that so? Why is the component rendered only 3 times? What's exectly going on here?
React-Redux's connect function relies on shallow-equality comparisons. Each time the store updates and a component's mapState function runs, that connected component checks to see if the contents of the returned object changed. If mapState returned something different, then the wrapped component must need to re-render.
Reselect uses "memoization", which means it saves a copy of the last inputs and outputs, and if it sees the same inputs twice in a row, it returns the last output rather than recalculating things. So, a Reselect-based selector function will return the same object references if the inputs didn't change, which means that it's more likely that connect will see that nothing is different and the wrapped component won't re-render.
See the new Redux FAQ section on Immutable Data for more info on how immutability and comparisons work with Redux and React-Redux.

Categories