Difference between these Two syntaxes in React [duplicate] - javascript

This question already has answers here:
What's the difference between passing a value and passing a callback in a React setState hook function?
(2 answers)
Closed 4 months ago.
I'm not an expert in React Js and want to know the difference between these two syntaxes in the ES6 syntax.
const items = array.map(thing => <p key={thing}>{thing}</p>)
function addItem(){
setArray(previtems => { return [...previtems, `Thing ${array.length + 1}`]});
}
and
const items = array.map(thing => <p key={thing}>{thing}</p>)
function addItem(){
setArray([...items, `Thing ${array.length + 1}`]);
}

The first one is functional setState. It gives guarantee that the value of prevItems will be the most updated one. This pattern is to be used whenever next state depends on the previous state.

Related

How to get state name from function argument when using setState in React [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 11 days ago.
I have the following state in my React Component:
class App extends Component {
constructor(props) {
super(props);
this.state = {
temperatureBedroom: 22.0,
temperatureLivingRoom: 23.0,
...
Now, I would like to update the state with the this.setState function.
The most straightforward way to do it is to just use the following code:
increaseTemp = () => {
let increment = 0.5;
this.setState({
temperatureBedroom: this.state.temperatureBedroom + increment
});
...
However, the problem is that with this approach I have to define a new (handler) function for each of the states (variables), i.e., as in my example -- rooms, for which I'd like to set a new value (temperature).
I was wondering if there is a more efficient way in React to address this issue.
The desired outcome would be to have something like that for the Buttons control:
<Button
variant="outline-secondary"
onClick={() =>
this.increaseTemp("temperatureBedroom")
}
>
+
</Button>
and I would like to use this argument like that:
increaseTemp = (roomName) => {
let increment = 0.5;
this.setState({
roomName: this.state.roomName + increment
});
...
The documentation doesn't mention a simple way to do it. It shows an example of writing separate handler functions for each state variable, see e.g.: https://beta.reactjs.org/learn/updating-objects-in-state
I have found similar questions, but some other aspects of the setState are discussed there, none of them addresses specifically the issue I would like to resolve:
How to setState from function parameter in React
Using function name as parameter of setState method?
Maybe I could try using a function as a setState parameter, but I am not sure if it helps with my problem: https://medium.com/#wisecobbler/using-a-function-in-setstate-instead-of-an-object-1f5cfd6e55d1
I would appreciated any suggestions how to avoid writing redundant handler functions.

Why console.log() is logging 4 times and it's different? [duplicate]

This question already has answers here:
My React Component is rendering twice because of Strict Mode
(6 answers)
Closed 2 months ago.
export default function course() {
const router = useRouter()
slu= router.asPath.split("/")[2]
console.log(slu)
return (<design goes here>);
}
So the problem here is that when I use this method it gives me this output
What I want is the value 1731547675 but instead of that it's giving me [slug]
What's wrong that I am doing here
It Prints multiple times because the ui is refreshed everytime You set a state
Wrap Your Console.log into a useEffect block
const [slu, setslu] = useState(0);
useEffect(()=>
setslu(router.asPath.split("/")[2])
}
Hopefully this helps. Note: Use const instead of let in creating a state

concatenating 2 arrays unexpected result [duplicate]

This question already has answers here:
React hooks stale state
(1 answer)
State not updating when using React state hook within setInterval
(14 answers)
Wrong React hooks behaviour with event listener
(9 answers)
Closed 1 year ago.
I am trying to update my array state with a list of records I am getting from an API, I am trying it as follows:
const [record, setRecord] = useState([])
const addRecords= async ()=>{
const apiResult = await apicall()
setRecord(record.length ? [...apiResult, ...record] : apiResult)
}
however every time the api is called is overwritting my 'record' with the last items added from the api instead of putting them together.
I also tried using .concat() with same result
const addRecords=async()=>{
const apiResult = await apicall()
setRecord(record.concat(apiResult ? apiResult:[])
}
there is sth here I am not managing to understand, hope someone can clarify what can it be.
I think you want to use a function in your setter to get your previous value (I dont understand enough to give you the reason why, but I think it has something to do with your record being a frame or two out of date)
const addRecords=async()=>{
const apiResult = await apicall()
//prevRecord is more recent than record (I think)
setRecord(prevRecord=>prevRecord.concat(apiResult || [])
}

Creating a dumb component [duplicate]

This question already has answers here:
Proper use of const for defining functions
(5 answers)
Closed 5 years ago.
I was wondering if there is any difference in performance when dealing with dumb component in React, since there are 2 possible ways to achieve the same result.
function Comp(props) {
...
}
const Comp = props => {
...
}
Really they are two ways to define a function and there should be no difference in the performances.
There's definitely no difference between the two in your example. Hence this code also gets compiled and you end up having the same thing:
function CompA(props) {}
const CompB = props => {}
gets transpiled to:
function CompA(props) {}
var CompB = function CompB(props) {};
edit: There is difference in both functions tho. In performance they are the same but in behavior the code is different. We have hoisting and different context involved.
edit2: Well, it looks like there IS a difference. Check out https://jsperf.com/react-stateless-compare

Get react state with dynamic key [duplicate]

This question already has answers here:
Get state value by a dynamic key in react
(2 answers)
Closed 5 years ago.
I already know how to setState with a dynamic key name but how do I set a value as the state with a dynamic key?
Example
function thing(key) {
let stuff = this.state.key;
//Do stuff
}
Didn't even think of think of this as first but all I did was
function thing(key) {
let stuff = this.state[key];
//Do stuff
}
and it worked!

Categories