Mutating state on React manually, then calling setState - javascript

I'm studying React JS making a simple todo list and part of my code is as follows:
changeStatus(e, index) {
this.state.tasks[index].status = e.target.value;
this.setState((prevState) => ({
tasks: prevState.tasks
}));
}
As React documentation says, we shouldn't change state manually, we should call setState instead, so, I'm receiving a warning on console saying that, even calling setState after the manual changing.
I'm doing so because, for me, is more practical doing that than separating the task, doing a splice on my array, and calling setState with the new values.
Is there a problem with my approach? How would you recommend updating state in a efficient and non-repetitive way?

Try this :
changeStatus(e, index) {
const tmp = { ...this.state };
tmp.tasks[index].status = e.target.value;
this.setState(tmp);
}

You should not mutate the state directly, to do that create a new object from the state and then update that and set it back to state like
changeStatus(e, index) {
var tasks = {...this.state.tasks}
tasks[index].status = e.target.value;
this.setState({tasks});
}
In case you are wondering as to what {...this.state.tasks} do then check this answer:
What is the meaning of this syntax "{...x}" in Reactjs
However you can also make a copy of the state using the ES5 Object.assign() operator like
var tasks = Object.assign({}, this.state.tasks)

Related

React: setState called twice even after spreading previous state

So, i have faced similar issues in the past, but could always figure out where i am missing to spread or assign a new object, while trying to update previous state. But i can't seem to figure out what i am doing wrong this time.
I have a state, in a functional component, that looks like this:
formData = {name: '', features: []}
And trying to update the features array with the following snippet:
function handleUpdate(featureUID) {
console.log('Called parent')
setFormData(prev => {
const spread = Object.assign({}, prev)
let features = [...spread.features]
if (features.includes(featureUID)) {
features = features.filter(x => x !== featureUID)
} else {
features = [...features, featureUID]
}
console.log('Features:', features)
spread.features = [...features]
return spread
})
}
So as you can see, i am initially assigning a shallow-copied version of prev to spread and further down, i also create a shallow copy of the features array.
But seems like after the first invocation of this method, on all consequent calls triggers the setState twice.
What am i missing here?
Edit 1
Forgot to mention the function that holds the setFormData aka setState is only being called once, confirmed via console logging. The way i am calling it:
{otherList?.map(single => <Button key={single.uid} onClick={() => handleUpdate(single.uid)}/>)}
Edit 2
I am aware of the fact that StrictMode causes the twice calling of setState. But i also know why it's that way. So not willing to remove StrictMode
Edit 3
Tried this and seems to work:
setFormData(prev => ({
...prev,
features: prev.features.includes(featureUID)
? prev.features.filter(x => x !== featureUID)
: [...prev.features, featureUID]
}))
But what i don't understand is, Why ? What did i miss in my first approach?

Why should i create a copy of the old array before changing it using useState in react?

Why this works
const handleToggle = (id) => {
const newTodos = [...todos]
newTodos.map(todo => {
if (todo.id === id) {
todo.completed = !todo.completed
}
});
setTodos(newTodos);
}
And this doesnt
const handleToggle = (id) => {
setTodos(prevTodos => prevTodos.map(todo => {
if (todo.id === id) {
todo.completed = !todo.completed
}
}))
}
Why do i have to create a copy of the old todos array if i want to change some item inside it?
You are doing a copy of the array in both cases, and in both cases you are mutating the state directly which should be avoided. In the second version you also forgot to actually return the todo, so you will get an array of undefined.
Instead you should shallow copy the todo you want to update.
const handleToggle = (id) => {
setTodos(prevTodos => prevTodos.map(todo => {
if (todo.id === id) {
return {...todo, completed: !todo.completed}
}
return todo
}))
}
Why mutating state is not recommanded? source
Debugging: If you use console.log and don’t mutate state, your past
logs won’t get clobbered by the more recent state changes. So you can
clearly see how state has changed between renders.
Optimizations: Common React optimization strategies rely on skipping
work if previous props or state are the same as the next ones. If you
never mutate state, it is very fast to check whether there were any
changes. If prevObj === obj, you can be sure that nothing could have
changed inside of it.
New Features: The new React features we’re
building rely on state being treated like a snapshot. If you’re
mutating past versions of state, that may prevent you from using the
new features.
Requirement Changes: Some application features, like implementing
Undo/Redo, showing a history of changes, or letting the user reset a
form to earlier values, are easier to do when nothing is mutated. This
is because you can keep past copies of state in memory, and reuse them
when appropriate. If you start with a mutative approach, features like
this can be difficult to add later on.
Simpler Implementation: Because
React does not rely on mutation, it does not need to do anything
special with your objects. It does not need to hijack their
properties, always wrap them into Proxies, or do other work at
initialization as many “reactive” solutions do. This is also why React
lets you put any object into state—no matter how large—without
additional performance or correctness pitfalls.
In practice, you can often “get away” with mutating state in React,
but we strongly advise you not to do that so that you can use new
React features developed with this approach in mind. Future
contributors and perhaps even your future self will thank you!
when you're changing an object using a hook correctly (- in this case useState) you are causing a re-render of the component.
if you are changing the object directly through direct access to the value itself and not the setter function - the component will not re-render and it will likely cause a bug.
and the .map(function(...)=>{..}) is a supposed to return an array by the items that you are returning from the function within. since you're not returning anything in the second example - each item of the array will be undefined - hence you'll have an array of the same length and all the items within will be undefined.
these kinds of bugs will not happen if you remember how to use array functions and react hooks correctly,
it's usually really small things that will make you waste hours on end,
I'd really recommend reading the documentation.

Organizing and setting state from another file

I have some data (objects) that live in their own file (Origin.js).
This data is being exported using the spread operator within another object named OriginState:
Origin.js
//info
const info = {
title: '',
year: '',
};
//images
const images = {
logo: '',
heroImage: '',
};
//text
const text = {
header: '',
body: '',
};
export const OriginState = {
...info,
...images,
...text,
};
I am importing my OriginState object in another file and using it as state for my app like this:
OtherFile.js
import { OriginState } from './Origin.js';
const [state, setState] = useState({
...OriginState,
});
Here is an example handler where I am using this state to update some specified state values in an input later:
const handleChange = (e) => {
const { name, value } = e.target;
setState((state) => ({
...state,
[name]: value,
}));
};
Now, my question is... Is it incorrect to store state like this?
Additionally, am I using setState incorrectly in my handler function?
In most cases I've seen state declared and updated like this which is obviously easier to read:
const [count, setCount] = useState(0);
setCount(count + 1)
But I have a lot of state and didn't think it would be a good idea to have multiple setState hooks.
Is there a better way to do this? What I currently have just feels wrong.
Is it incorrect to store state like this?
const handleChange = (e) => {
const { name, value } = e.target;
setState((state) => ({
...state,
[name]: value,
}));
};
Nope, not at all, in fact, it is often the preferable pattern for state updates.
Any time your state update depends on the previous state, i.e. the classic counter example, or in your case, when there is nested state, you should use a functional state update to update from the previous state instead of the state from the previous render cycle.
Additionally, am I using setState incorrectly in my handler function?
In most cases I've seen state declared and updated like this which is
obviously easier to read:
const [count, setCount] = useState(0);
setCount(count + 1)
I see no issue with your state update logic in the handler. In this count example it would (should) be considered incorrect to update a count like this. See this codesandbox demo that attempts to show the issue between non-functional and functional state updates.
The correct state update should be setCount(count => count + 1)
But I have a lot of state and didn't think it would be a good idea to
have multiple setState hooks.
Is there a better way to do this? What I currently have just feels
wrong.
When it comes to form inputs and state I think it makes sense to have a single flat object. There isn't really a right or wrong answer in general though when it comes to using a single useState hook with "complex" state shape, or to use a single useState hook for each "chunk" of state. It's an opinionated answer, mostly do what makes sense for a specific use-case.
Generally though I'd say if a set of values are even loosely related then perhaps it makes sense to store them in a common object, but this is my opinion.
A potential issue I see with your imported data though is the chance that you may inadvertently overwrite some key-value pairs by the use of the Spread syntax.
export const OriginState = {
...info,
...images, // <-- could overwrite values from info
...text, // <-- could overwrite values from info and images
};
Your approach seems quite legit, and this is one of the best practices that if your newState is depend on the oldState use setState callback and get the old state from callback input because otherwise as you showed above if you use it like this:
const [count, setCount] = useState(0);
setCount(count + 1)
you may increase the chance to get stale data which will increase the potential for bug

Asynchronous way to get the latest change in State with React Hooks

I have started learning React and developing an application using ReactJS. Recently i have moved to React Hooks. I know that in Class Component we can get the latest data from the state with the 2nd argument which is present in setState() like
state = {name: ''};
this.setState({name: name}, () => {console.log(this.state)});
I wanted to know if there is any arguments in React Hooks with which we can get the latest data from it.
I am using React Hooks in the below mentioned way, but upon console logging it always return the previous state
Hooks Eg:
const [socialData, setSocialData] = useState([
{ id: new Date().getTime().toString(), ...newItem }
]);
const onChangeCallback = (index, type, data) => {
let newSocialData = [...socialData];
newSocialData[index] = { ...newSocialData[index], [type]: data };
setSocialData(newSocialData);
onInputChange(newSocialData, formKey);
console.log(newSocialData);
};
The this.setState() second argument is not exactly to get the latest data from the state, but to run some code after the state has been effectively changed.
Remember that setting the state is an asynchronous operation. It is because React needs to wait for other potential state change requests so it can optimize changes and perform them in a single DOM update.
With this.setState() you can pass a function as the first argument, which will receive the latest known state value and should return the new state value.
this.setState((previousState) => {
const newState = previousState + 1;
return newState;
}, () => {
console.log('State has been updated!')
});
With that being said, there are special and rare cases when you need to know exactly when the state change has taken place. In many years of working with React I only faced this scenario once and I consider it a desperate attempt to make things work.
Usually, during a callback execution, like your onChangeCallback you want to change the state as the last thing your function does. If you already know the new state value, why do you want to wait for the real state to change to use it?
The new state value should be a problem to be handled during the next render.
If you want to run some code only when that particular state value changes you can do something like this:
import React, {useState, useEffect, useCallback} from 'react';
function MyComponent() {
const [value, setValue] = useState(false);
const onChangeHandler = useCallback((e) => {
setValue(!!e.target.checked);
}, []);
useEffect(() => {
// THIS WILL RUN ONLY WHEN value CHANGES. VERY SIMILAR TO WHAT YOU ARE TRYING TO DO WITH THE this.setState SECOND ARGUMENT.
}, [value]);
return (
<input type='checkbox' onChange={onChangeHandler} />
);
}
There is also a way to create a custom useState hook, to allow you passing a second argument to setValue and mimic the behavior of this.setState, but internally it would do exactly what I did in the above component. Please let me know if you have any doubt.

Redux/React-Redux - using "state = XXX" in the reducer

We're using Redux.js with React.js (React-Redux), and in the reducer we're using the following code (we are using redux-actions to reduce boilerplate):
const update = require('react/lib/update');
const myReducer = handleActions
({
[myAction]: (state, action) => {
state = update(state, {
something: {$set: !state.someProperty}
});
return someFunction(state);
}
})
We are using update from React Immutability Helpers but assigning the result into the state using state =.
Is this against the basic Redux guidlines - i.e. mutating the state? It seems so, but the code seems to work perfectly and quickly, and the redux devtools shows the state changes correctly...
Your example is okay, because you're not actually mutating the contents of the object that the state variable points to. Instead, you're just updating the local variable named state to point to a different object instead.
It's important to understand how variables and references work in Javascript, which will help clear up what's going on here.
Personally, I'd suggest doing const newState = update(....) for clarity.

Categories

Resources