问题
Using hooks, If I call setState
with the same value as the state
, will it rerender the component?
If yes, how can I avoid that?
e.g.
const [state, setState] = useState(foo)
...
// any where in the code
setState(foo)
Considering that foo
can be any thing, such as {}
, true
, props.bar
or a variable from out side of the component (constant).
回答1:
It won't re-render the component if you call setState
with the same value.
Try this out:
import React, { useState, useEffect } from "react";
const foo = { foo: 'bar' };
export default ({ name }) => {
const [state, setState] = useState(foo);
console.log("rendered!");
useEffect(() => {
setState(foo);
console.log("state reset!");
});
const handleClick = () => {
console.log("handleClick!");
setState(foo);
// setState({ ...foo, bar : 'baz' });
}
return (<div>
<h1>Hello {name}!</h1>
<button onClick={handleClick}>Click Me</button>
</div>);
};
You'll notice that even when the button is clicked since the value has not changed. it's not re-rendering the Component. If you change the argument that you call setState
with, it will re-render the component.
Here's a Code Sample for your ref.
Try commenting the first setState
and un-commenting the second one inside the handleClick
method to see the difference.
回答2:
It's a js syntax related question, Just like ===
operation.
let times = 0
const init = {name: 'Bob'}
function App() {
const [state, setState] = useState(init)
function modify() {
setState({name: 'Bob'})
}
function modify2() {
setState(init)
}
times ++
return (
<div className="App">
<p>{ times }</p>
<button onClick={modify}>Same Value Will Rerender</button>
<button onClick={modify2}>Same Reference Never Rerender</button>
</div>
);
}
Here's a Code Sandbox
You can rewrite a wrapper method:
let times = 0
const init = {name: 'Bob'}
function App() {
const [state, setState] = useState(init)
function modify3() {
setState2({ name: 'Bob' })
}
function setState2(value) {
if (value.name === state.name) {
return
}
setState(value)
}
times ++
return (
<div className="App">
<p>{ times }</p>
<button onClick={modify3}>Same Value Will Not Rerender Yet</button>
</div>
);
}
来源:https://stackoverflow.com/questions/59489959/set-state-with-same-value-using-hooks-will-cause-a-rerender