Why is this a valid approach for updating state? - javascript

In the React docs, it mentioned that next state shouldn't be directly computed from current state. This is because state updates are asynchronous, so you can't be assured that you are using the correct value of state.
However, in the official tutorial, you will see this function:
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
this.setState({
history: history.concat([
{
squares: squares
}
]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext
});
}
You can see that the variable history is a function of state.history and state.stepNumber. Isn't this a contradiction of what was mentioned in the docs, or am I missing something?

People get a little too dogmatic about it in my opinion, but there have been enough hard to trace bugs that maybe it's justified. Ultimately, you have to know why its recommended in order to know if its ok not to in special cases.
Why is it recommended?
State updates are asynchronous and can be batched, and you may be using stale values if you update state multiple times and one or more of your updates are based on previous values. In a functional component, you have the same risks do to stale closures.
Example where state should be updated 5 times, but is only incremented once:
Functional component example:
const {useState} = React;
const Example = () => {
const [value, setValue] = useState(0);
const onClick = () => {
[1,2,3,4,5].forEach(() => {
console.log('update');
setValue(value + 1);
});
}
return (
<div>
<button onClick={onClick}>Update 5 times</button>
<div>Count: {value}</div>
</div>
)
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Class component example:
const {useState, useEffect} = React;
class Example extends React.Component {
state = {
count: 0
}
onClick = () => {
[1,2,3,4,5].forEach(() => {
this.setState({count: this.state.count + 1});
});
}
render() {
return (
<div>
<button onClick={this.onClick}>Update 5 times</button>
<div>Count: {this.state.count}</div>
</div>
);
}
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
Is it ok to use normal state updates based on previous state?
It depends on your use case. If you know for an absolute certainty that you will only update state once, then technically it's safe. The problem is, while it may be safe today, tomorrow you or another developer may unknowingly change that...
At the end of the day, I think you have to ask yourself: "Do I gain any extra benefit from not using a functional update?", if so then understand the risks of future bugs and go for it (you should probably document it heavily too). But almost every time, the answer will be just use the functional update.

because this: const history = this.state.history.slice(0, this.state.stepNumber + 1); isn't actually mutating any state. it's just assigning it to a const for the local function to use. it's not actually manipulating the state itself
a few lines below it uses this.setState({}) to directly change state in the standard way
the assigning to a const is different than if you just did this: this.state.history.slice(0, this.state.stepNumber + 1) which would be directly manipulating it

Related

cannot change usestate to change the state of the components

This is code of my AddBlog Component
import React, { useState } from "react";
function AddBlogs() {
const[state, setState] = useState({blogs:[]})
const AddAnother = () => {
return (
<div>
<label>Topic</label>
<input></input>
<button onClick={addblog}>Add another topic</button>
</div>
);
}
const addblog = () =>{
setState({
blogs:[...state.blogs,<AddAnother></AddAnother>]
});
console.log("Hello");
}
return (
<div>
<form>
<div>
<label>Topic</label>
<input></input>
<button onClick={addblog}>Add another topic</button>
</div>
<div>
{state.blogs}
</div>
</form>
</div>
);
}
export default AddBlogs;
When I click that Add another topic button AddAnother components blinks for just 0.5 second or less. Any solution for this?
I see a couple things that will cause problems. First, when you update state, you shouldn't use the current state. Instead, you should use the setState that accepts a function with the old state as the first parameter, such as the following:
const addblog = () => {
setState((oldState) => {
return { blogs: [...oldState.blogs, <AddAnother />] };
});
console.log("Hello");
};
This won't solve your problem, though. The issue you're seeing is due to you not having a key in your array of components. So try this:
const addblog = () => {
setState((oldState) => {
return { blogs: [...oldState.blogs, <AddAnother key={oldState.blogs.length} />] };
});
console.log("Hello");
};
As David pointed out, the form is also posting, which is causing part of the problem as well.
Because the <form> is posting. If you don't need this to be an actual <form> then remove that element entirely. But if for some reason you want to keep that element, change the button type(s):
<button type="button" onClick={addblog}>Add another topic</button>
By default a <button> is of type submit unless otherwise specified.
Edit: Additionally, as answered here, you need to change the way you're setting state to use the callback overload:
setState((oldState) => {
return { blogs: [...oldState.blogs, <AddAnother key={oldState.blogs.length} />] };
});
In most cases it makes little difference whether you set the state directly or use the callback which sets based on previous state. The latter is often used when queueing up multiple state updates in a loop, for example. But you have an edge case here.
Your AddAnother component internally references a "stale version" of addblog which always references the original state. Changing to the callback version of setState gets around this.
Other ways around this would be to restructure your code to remove the circular dependency, refactor components into their own discrete code, make use of tools like useCallback to define functions which have dependencies on state values, etc.

When to optimize renders in react with useMemo and useCallback

I've read a few articles on when to optimize rendering in React, however, I still have some doubts.
const RepairNoticeContainer = () => {
const dispatch = useDispatch();
const history = useHistory();
const { siteType, siteId } = useParams();
const data = useSelector(pageSelectors.getData);
const showRepairNotice = data.grid.cols.lg !== 36;
const handleRepairClick = () => {
dispatch(
pagesActions.copyAndRepairCurrentPage(newPageId => {
history.push(`/editor/${siteType}/${siteId}/pages/${newPageId}`);
})
);
};
return showRepairNotice ? <RepairNotice onRepairClick={handleRepairClick} /> : null;
};
As far as I can understand, it would be beneficial to use useCallbackfor handleRepairClick to avoid rerenders of <RepairNotice/>. But what about showRepairNoticevariable? Should it be wrapped in a useMemo for optimization?
const RepairNotice = ({ onRepairClick }) => {
const translate = useTranslator();
let message = translate("repair_warning");
message = message.charAt(0).toLowerCase() + message.slice(1);
return (
<MessageBox type="warning" icon="information11" className="mb-0 mt-2">
<div className="row">
<div className="col">
<b>{translate("warning")}:</b> {message}
</div>
<div className="col-auto text-right">
<Button color="danger" onClick={onRepairClick} size="small">
{translate("repair_now")}
</Button>
</div>
</div>
</MessageBox>
);
A simillar question for this example. Would it be beneficial to wrap message inside of useMemo?
const Page = ({ status }) => {
const unsavedData = status?.unsavedData ? true : false;
return (
<Fade>
<div className="Page">
<NavConfirmModal active={unsavedData} onSavePage={onSavePage} />
</div>
</Fade>
);
};
Lastly, should useMemo be used unsavedData?
Explanations would be much appreciated.
As far as I can understand, it would be beneficial to use useCallback for handleRepairClick to avoid rerenders of
That's right. while wrapping handleRepairClick you will, simply speak, prevent creating a new instance of this function so it will save RepairNotice nested component from redundant rerenders because it relies on this function in props. Another good case for useMemo is when you're rendering a list of items and each relies on the same handler function declared in their parent.
Very good useCallback explanation here.
But what about showRepairNotice variable? Should it be wrapped in a
useMemo for optimization?
It's just a simple "equation" check which is really cheap from performance side - so there is really no need in useMemo here.
Would it be beneficial to wrap message inside of useMemo?
Yes, it would. Since there are at least 3 actions javascript has to fire upon the message (charAt, toLowerCase, slice) and you don't really want this calculations to fire every time the RepairNotice component gets rerendered.
should useMemo be used unsavedData?
It might be preferable to wrap unsavedData into useMemo if NavConfirmModal will be wrapped in React.Memo or in the case of "heavy calculations". So for the current case - it would not really make a difference. (btw calculating unsavedData could be written just like !!status?.unsavedData to get boolean).
And very good useMemo explanation here.

Can't understand "state" in reactjs

In whichever site I visit to get my doubt clear about state in react I always found this defination in common which is:
"an object of a set of observable properties that control the behavior of the component". And I still don't understand the state in react. Consider an example below
import React,{useState} from 'react';
export const City = ()=>{
const [altitude,setAltitude] = useState("");
const getAltitude=()=>{
navigator.geolocation.watchPosition((position)=>{
const alt = {
lat:position.coords.latitude,
long:position.coords.longitude
}
setAltitude(alt);
console.log(altitude);
})
}
return(
<div id="location">
{getAltitude()}
<h3>This is location</h3>
</div>
)
}
But the above program can also be written without using state as shown below
import React,{useState} from 'react';
export const City = ()=>{
let lat;
let long;
const getAltitude=()=>{
navigator.geolocation.watchPosition((position)=>{
lat = position.coords.latitude;
long = position.coords.longitude;
})
console.log(lat,long);
}
return(
<div id="location">
{getAltitude()}
<h3>This is location</h3>
</div>
)
}
If we can write in this way too then what is the use of state in react.
If I'm wrong I request you to explain me in detail. I'm not able to sleep unless this doubt doesn't get clear.
For the understanding purpose I've created these two snippets, one using state variable and the other using regular js variables.
Using state variable
const { useState } = React;
const Counter = () => {
const [count, setCount] = useState(0);
const onClick = () => {
//Update the state
setCount(c => c + 1);
}
return (
<div>
Count: {count}
<div>
<button onClick={onClick}>Increment</button>
</div>
</div>
)
}
ReactDOM.render(<Counter />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Using regular variable
const { useState } = React;
const Counter = () => {
let count = 0;
const onClick = () => {
//Update the variable
count += 1;
console.log(count);
}
return (
<div>
Count: {count}
<div>
<button onClick={onClick}>Increment</button>
</div>
</div>
)
}
ReactDOM.render(<Counter />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>
In both of the above scenarios we are updating the count on click of the button, but then in scenario 1, the updated value is displayed on the DOM where as in scenario 2, it's not.
So, basically when you want to re-render the component on change of the variable we keep those variables in the state. React will be able to understand the state changes and update the DOM accordingly
As stated correctly in your citation, React maintains a state that is used to to figure out, beside some other features, when to re-render your component. In your examples, it seems like you wanted to add an event listener for watchPosition, and show the calculated values in your City component. If I am correct please consider this example:
import React,{useState} from 'react';
export const City = ()=>{
const [altitude,setAltitude] = useState({});
const calculateAltitude=()=>{
navigator.geolocation.watchPosition((position)=>{
const alt = {
lat:position.coords.latitude,
long:position.coords.longitude
}
setAltitude(alt); // you set the state here
})
}
calculateAltitude(); // This function is called on each render. It's better to put it into a "componentDidMount" equivalent (second example)
return(
<div id="location">
<h3>This is the location</h3>
<div>Lat: {altitude.lat}</div> {/*You use the state here*/}
<div>Lat: {altitude.long}</div>
</div>
)
}
Each time watchPosition is executed, your state altitude is updated and the component will re-render. This means, that the render function is executed and the current state of altitude is used to display the latitude and longitude. In the first example, calculateAltitude() will be executed each time, your component renders. Since that is not best practice, you should put that call into a useEffect hook, with an empty-array dependency. It is an equivalent to the componentDidMount() fucntion for React class components (React.Component). You can find a good explanation here.
So, in order to have a clean code, you should use this component:
import React,{useState, useEffect} from 'react';
export const City = ()=>{
const [altitude,setAltitude] = useState({});
const calculateAltitude=()=>{
navigator.geolocation.watchPosition((position)=>{ // each time this geolocation lib calls your function, your state will be updated.
const alt = {
lat:position.coords.latitude,
long:position.coords.longitude
}
setAltitude(alt); // you set the state here
})
}
useEffect(() =>
{
calculateAltitude() // register your event listener once.
},[]) // on Component mount. Executed once.
return(
<div id="location">
<h3>This is the location</h3>
<div>Lat: {altitude.lat}</div> {/*You use the state here. It is updated each time your geolocation lib calls your listener.*/}
<div>Lat: {altitude.long}</div>
</div>
)
}
I recommend to read carefully about the React states. Here are some good links:
offical doc
article about react states in function
components
One of the features that is at the fundament of React is that it allows you to update your UI, or, in other terms, the HTML output of your app, after a change to a variable. In React, state is a way to declare the variables that, depending on your business logic, can ultimately update the UI. React does this by keeping track of the state and rerendering parts of the HTML that need the update.
In your example, you made altitude part of your state, but your logic does not update the UI anywhere—it just determines a geolocation on first load. If this is what you want, that's fine, you won't need state for that. If, however, you want to make updates to your HTML, e.g. if you'd like to show the realtime location of a user on a map, you could make use of React's state: you write location updates to the state, and will need some custom logic that handles what happens if the altitude value has changed. You could write this custom logic as a side effect.
state variables will be accessible into jsx ( i mean in rendered part of the component), so in your example, altitude will be accessible in the html part, but if you didn't assign it to state variable wont be able to access it
return(
<div id="location">
<h3>This is location {altitude.alt}</h3>
</div>
)

How to avoid unnecessary re-rendering of React Component

I've been learning new features of React 16.8. I believe React's Pure Component should automatically avoid unnecessary re-render operations.
In the following example, the App itself is a stateless component. I use useState to maintain two state objects text and nested: {text}.
There are 3 tests. The first 2 tests work. No matter how many times, I change the state, no re-render operation will be required.
Now, the third test tries to set the state of text with the same string value, but the reference is different. I expect nothing to be re-rendered, but actually, the <Headline/> will be re-rendered.
Shall I use certain memorize technique to avoid? I feel it will be too much code to archive that. And programmer must be very careful to write high-quality React code. ..
class Headline extends React.PureComponent {
render() {
const {text} = this.props;
return <h1>{text} (render time: {Date.now()})</h1>;
}
}
const simpleText = 'hello world'
const App = () => {
const [text, setText] = React.useState(simpleText)
const [nested, setNested] = React.useState({text: simpleText})
return (
<div>
<Headline text={text}/>
<Headline text={nested.text}/>
<button onClick={()=>setText(simpleText)}>
test 1: the first line should not change (expected)
</button>
<button onClick={()=>setNested({text: simpleText})}>
test 2: the second line will not change (expected)
</button>
<button onClick={()=>setText(new String(simpleText))}>
test 3: the first line will change on every click (why?)
</button>
</div>
)
}
ReactDOM.render(<App />, document.querySelector("#app"))
Here is a live playground in jsfiddle:
https://jsfiddle.net/fL0psxwo/1/
Thank you React folks, cheers!
Update 1:
Thanks Dennis for mentioning why-did-you-render
The author points some very useful articles. I think it could be very educational to everybody.
https://medium.com/welldone-software/why-did-you-render-mr-big-pure-react-component-part-2-common-fixing-scenarios-667bfdec2e0f
Update 2:
I created a new hook called withDirtyCheck so that my code will automatically do content dirty check.
import isEqual from 'lodash-es/isEqual';
export const withDirtyCheck = ([getter, setter]) => {
const setStateIfDirty = (nextState) =>
setter((prevState) => (isEqual(prevState, nextState) ? prevState : nextState));
return [getter, setStateIfDirty];
};
Checkout my latest library https://github.com/stanleyxu2005/react-einfach
The problem is that with new operator you creating a String Object which is always different from the previous state.
'hello world' === new String('hello world') // false, always.
'hello world' === String('hello world') // true
Check this example:
setText(prevState => {
// Will render
// const currState = new String(simpleText);
// Won't render
const currState = String(simpleText);
console.log(prevState === currState); // if true, no re-render
// if false, re-render
return currState;
});
Refer to What is the difference between string primitives and String objects in JavaScript?

Where should functions in function components go?

I'm trying to convert this cool <canvas> animation I found here into a React reusable component. It looks like this component would require one parent component for the canvas, and many children components for the function Ball().
It would probably be better for performance reasons to make the Balls into stateless components as there will be many of them. I'm not as familiar with making stateless components and wondered where I should define the this.update() and this.draw functions defined in function Ball().
Do functions for stateless components go inside the component or outside? In other words, which of the following is better?
1:
const Ball = (props) => {
const update = () => {
...
}
const draw = () => {
...
}
return (
...
);
}
2:
function update() {
...
}
function draw() {
...
}
const Ball = (props) => {
return (
...
);
}
What are the pros and cons of each and is one of them better for specific use cases such as mine?
The first thing to note is that stateless functional components cannot have methods: You shouldn't count on calling update or draw on a rendered Ball if it is a stateless functional component.
In most cases you should declare the functions outside the component function so you declare them only once and always reuse the same reference. When you declare the function inside, every time the component is rendered the function will be defined again.
There are cases in which you will need to define a function inside the component to, for example, assign it as an event handler that behaves differently based on the properties of the component. But still you could define the function outside Ball and bind it with the properties, making the code much cleaner and making the update or draw functions reusable:
// you can use update somewhere else
const update = (propX, a, b) => { ... };
const Ball = props => (
<Something onClick={update.bind(null, props.x)} />
);
If you're using hooks, you can use useCallback to ensure the function is only redefined when any of its dependencies change (props.x in this case):
const Ball = props => {
const onClick = useCallback((a, b) => {
// do something with a, b and props.x
}, [props.x]);
return (
<Something onClick={onClick} />
);
}
This is the wrong way:
const Ball = props => {
function update(a, b) {
// props.x is visible here
}
return (
<Something onClick={update} />
);
}
When using useCallback, defining the update function in the useCallback hook itself or outside the component becomes a design decision more than anything: You should take into account if you're going to reuse update and/or if you need to access the scope of the component's closure to, for example, read/write to the state. Personally I choose to define it inside the component by default and make it reusable only if the need arises, to prevent over-engineering from the start. On top of that, reusing application logic is better done with more specific hooks, leaving components for presentational purposes. Defining the function outside the component while using hooks really depends on the grade of decoupling from React you want for your application logic.
Another common discussion about useCallback is whether to always use it for every function or not. That is, treat is as opt-in or always recommendable. I would argue to always use useCallback: I've seen many bugs caused by not wrapping a function in useCallback and not a single scenario where doing so affects the performance or logic in any way. In most cases, you want to keep a reference while the dependencies don't change, so you can use the function itself as a dependency for other effects, memos or callback. In many cases the callback will be passed as a prop to other elements, and if you memoized it with useCallback you won't change the props (thus re-render) other components independently of how cheap or costly that would be. I've seen many thousands of functions declared in components and not a single case in which using useCallback would have any down side. On the other hand most functions not memoized with useCallback would eventually be changed to do so, causing serious bugs or performance issues if the developer doesn't recognize the implications of not doing so. Technically there is a performance hit by using useCallback, as you would be creating and additional function but it is negligible compared to the re-declaration of the function that always has to happen either you use useCallback or not and the overall footprint of React and JavaScript. So, if you are really concerned about the performance impact of useCallback versus not using it, you should be questioning yourself if React is the right tool for the job.
You can place functions inside stateless functional components:
function Action() {
function handlePick(){
alert("test");
}
return (
<div>
<input type="button" onClick={handlePick} value="What you want to do ?" />
</div>
)
}
But it's not a good practice as the function handlePick() will be defined every time the component is rendered.
It would be better to define the function outside the component:
function handlePick(){
alert("test");
}
function Action() {
return (
<div>
<input type="button" onClick={handlePick} value="What you want to do ?" />
</div>
)
}
If you want to use props or state of component in function, that should be defined in component with useCallback.
function Component(props){
const onClick=useCallback(()=>{
// Do some things with props or state
},[])
return <Something {...{onClick}} />
}
On the other hand, if you don't want to use props or state in function, define that outside of component.
const computeSomethings=()=>{
// Do some things with params or side effects
}
function Component(props){
return <Something onClick={computeSomethings} />
}
For HTML tags you don't need useCallback because that will handle in react side and will not be assigned to HTML
function Component(props){
const onClick=()=>{
// Do some things with props or state
}
return <div {...{onClick}} />
}
Edit: Functions in hooks
For the use function in hooks for example useEffect, my suggestion is defining function inside useEffect, if you're worried about DRY, make your function pure call it in hook and give your params to it.
What about hooks deps? You should/could add all of your params to hooks deps, but useEffect just needs deps which should affect for them changes.
We can use the React hook useCallback as below in a functional component:
const home = (props) => {
const { small, img } = props
const [currentInd, setCurrentInd] = useState(0);
const imgArrayLength = img.length - 1;
useEffect(() => {
let id = setInterval(() => {
if (currentInd < imgArrayLength) {
setCurrentInd(currentInd => currentInd + 1)
}
else {
setCurrentInd(0)
}
}, 5000);
return () => clearInterval(id);
}, [currentInd]);
const onLeftClickHandler = useCallback(
() => {
if (currentInd === 0) {
}
else {
setCurrentInd(currentInd => currentInd - 1)
}
},
[currentInd],
);
const onRightClickHandler = useCallback(
() => {
if (currentInd < imgArrayLength) {
setCurrentInd(currentInd => currentInd + 1)
}
else {
}
},
[currentInd],
);
return (
<Wrapper img={img[currentInd]}>
<LeftSliderArrow className={currentInd > 0 ? "red" : 'no-red'} onClick={onLeftClickHandler}>
<img src={Icon_dir + "chevron_left_light.png"}></img>
</LeftSliderArrow>
<RightSliderArrow className={currentInd < imgArrayLength ? "red" : 'no-red'} onClick={onRightClickHandler}>
<img src={Icon_dir + "chevron_right_light.png"}></img>
</RightSliderArrow>
</Wrapper>);
}
export default home;
I'm getting 'img' from it's parent and that is an array.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
const a = () => {
setCount(count + 1);
};
return (
<div>
<p>You clicked {count} times</p>
<button onClick={a}>Click me</button>
</div>
);
}
export default Example;

Categories