redux unnecessarily rerenders whole component - reactjs

the problem is as follows:
this is what i have in my redux duck
export const myInit = () => (dispatch, getState) => {
db.ref(`/parts/`).on(
'value',
(snapshot) =>
(dispatch(getParts(mapObjectToArray(snapshot.val())))))
}
export const addAmount = (objecter) => (dispatch, getState) => {
let findKey = getState().partsState.parts.find(x => {
if (x.part === objecter)
return x.key
})
let xAmount
getState().partsState.parts.find(x => {
if (x.part === objecter)
return xAmount = x.amount
})
db.ref(`/parts/${findKey.key}/amount`).set(xAmount + 1)
}
myInit() is called once in the store so the parts are saved in the state.
I display those parts in my component in a table. In each tr there is a name of part, amount and a button to change amount of parts. Once you click the button, the amount of the given part changes. Everything seems to be working just fine unless, the amount change is called when parts are filtered with state of an input value.
When list is filtered, and amount of part is changed, the whole component rerenders. Search field is cleared and the list extends. I don't know what to do. Please tell me what am I missing.
the component:
class ListOfParts extends Component {
state = {
basicSearchInput: '',
ITEMS_PER_PAGE: 10,
currentPage: 0,
parts: []
}
setStateForSearch(event) {
this.setState({basicSearchInput: event.target.value})
}
render() {
let myArrayForState = ['actuator', 'back_plate']
let arrayForHeadings = ['Actuator', 'Back plate'
]
let parts = this.props.parts;
const filter = parts
.filter(part => {
return (part.part.toLowerCase().includes(this.state.basicSearchInput.toLowerCase()))
|| (part.group.toLowerCase().includes(this.state.basicSearchInput.toLowerCase()))
}
)
const numberOfParts = filter && filter.length
return (
<div>
<TextField
type={"search"}
value={this.state.basicSearchInput}
onChange={event => this.setStateForSearch(event)}
/>
<RaisedButton
onClick={this.handleOpen}
>
add
</RaisedButton>
<Row>
<table>
<tbody>
{filter && filter.length ?
filter.filter((el, i) => {
return (i >= this.state.ITEMS_PER_PAGE * this.state.currentPage
&&
i < this.state.ITEMS_PER_PAGE * (this.state.currentPage + 1))
}).map((partInStateArray, index) =>
<tr id={`${partInStateArray.part}`}
key={`${partInStateArray.part}${this.props.index}`}>
<td>{this.arrayForHeadings[this.myArrayForState.indexOf(partInStateArray.group)]} {partInStateArray.part}</td>
<td>{partInStateArray.amount}</td>
<td>
<button onClick={this.add}>+</button>
</td>
</tr>)
)
: 'loading'
}
</tbody>
</table>
</Row>
<div style={{textAlign: 'center'}}>
<Pagination
total={Math.ceil(numberOfParts / this.state.ITEMS_PER_PAGE)}
current={this.state.currentPage + 1}
display={10}
onChange={newPage => this.setState({currentPage: newPage - 1})}
/>
</div>
</div>
)
}
}
const mapStateToProps = state => ({
parts: state.partsState.parts,
})
const mapDispatchToProps = dispatch => ({
addAmount: (objectToAdd) => dispatch(addAmount(objectToAdd)),
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(ListOfParts)

Related

React dynamic nested form input

Im a newbie in React and Im creating a simple form that sends data to DB. I made it work almost as I wanted, the only problem is that I dont know how to update the state which has an array inside.
The idea is to make a form so I can add recipes which include the whole recipe data that I map through to render each recipe. In the data object I need simple strings most of the time but then I need also three arrays or objects, I prefer the arrays in this case.
I found many solutions for class components but still I could figure out how to update the arrays. I even figured out how to update one array from a string input separated only with commas, then .split(', ') and .trim() and map() through but I could not setFormFields({}) at two places at the same time since the createRecipe() is async. The split just did not happen before the array was sent to the DB as a string. Thats why I dont put the whole code here.
I will simplify the code to make you see clear.
const defaultFormFields = {
title: '',
imageUrl: '',
leadText: '',
};
const NewRecipeForm = () => {
const [formFields, setFormFields] = useState(defaultFormFields);
const { title, imageUrl, leadText } = formFields;
const [ingredients, setIngredients] = useState([])
const handleFormFieldsChange = (event) => {
setFormFields({ ...formFields, [event.target.name]: event.target.value })
}
const handleIngredientsChange = ( event) => {
**// here I need help**
setIngredients()
}
const addIngredient = () => {
setIngredients([...ingredients, ''])
}
const removeIngredient = (index) => {
**// here I need help**
}
const createRecipe = async (event) => {
event.preventDefault()
// addRecipe sends the object to Firestore DB
addRecipe('recipes', url, formFields)
resetFormFields()
}
const resetFormFields = () => {
setFormFields(defaultFormFields);
};
return (
<NewRecipeFormContainer>
<h1>New recipe</h1>
<form onSubmit={createRecipe}>
<h1>Title</h1>
<input label='Title' placeholder='Recipe title' name='title' value={title} onChange={handleChange} />
<input label='imageUrl' placeholder='imageUrl' name='imageUrl' value={imageUrl} onChange={handleFormFieldsChange} />
<input label='leadText' placeholder='leadText' name='leadText' value={leadText} onChange={handleFormFieldsChange} />
<h1>Ingredients</h1>
**// here I need help ?**
{
ingredients.map((ingredient, index) => {
return (
<div key={index}>
<input label='Ingredience' placeholder='Ingredience' name='ingredient' value={ingredient.ingredient} onChange={handleChange} />
**// here I need help ?**
<button onClick={removeIngredient} >remove</button>
</div>
)
})
}
<button onClick={addIngredient} >add</button>
</form>
<Button onClick={createRecipe}>ODESLAT</Button>
</NewRecipeFormContainer>
)
}
I will appreciate any hint or help. Ive been totally stuck for two days. Thank you!
Here's an example of how to update a single element in a list.
const updateSingleItemInList = (index, update) => {
setList(list.map((l, i) => i === index ? update : l));
};
const add = (element) => setList([...list, element]);
Try simplifying your state first:
const [ingredients, setIngredients] = useState([]);
const [tips, setTips] = useState([]);
Then it becomes simple to write the handlers:
const updateIngredient = (index, text) => {
setIngredients(list.map((ing, i) => i === index ? text : ing));
};
const addIngredient = () => setIngredients([...ingredients, ""]);
Then you can create the form object when the user wants to submit:
addRecipe('recipes', url, {
ingredients: ingredients.map(i => ({ingredients: i})),
// etc.
});
Put it all together and here is the minimum viable example of a component that manages a dynamic number of form elements (tested, works):
export const TextBody = () => {
const [list, setList] = useState([{ name: "anything" }]);
const add = () => setList(l => [...l, { name: "" }]);
const remove = i => setList(l => [...l.slice(0, i), ...l.slice(i + 1)]);
const update = (i, text) => setList(l => l.map((ll, ii) => (ii === i ? { name: text } : ll)));
return (
<>
<TouchableOpacity onPress={add}>
<Text text="add" />
</TouchableOpacity>
{list.map((l, i) => (
<>
<Text text={JSON.stringify(l)} />
<TouchableOpacity onPress={() => remove(i)}>
<Text text="remove" />
</TouchableOpacity>
<Input onChange={c => update(i, c.nativeEvent.text)} />
</>
))}
</>
);
};
You can return those CRUD functions and the state from a custom hook so you only have to write this once in a codebase.
Edit: Just for fun, here's the same component with a reusable hook:
const useListOfObjects = (emptyObject = {}, initialState = []) => {
const [list, setList] = useState(initialState);
const add = () => setList(l => [...l, emptyObject]);
const remove = i => setList(l => [...l.slice(0, i), ...l.slice(i + 1)]);
const update = (i, text, field) =>
setList(l => l.map((ll, ii) => (ii === i ? { ...ll, [field]: text } : ll)));
return {
list,
add,
remove,
update,
};
};
export const TextBody = () => {
const { list, add, remove, update } = useListOfObjects({ name: "", id: Math.random() });
return (
<>
<TouchableOpacity onPress={add}>
<TextBlockWithShowMore text="add" />
</TouchableOpacity>
{list.map((l, i) => (
<React.Fragment key={`${l.id}`}>
<TextBlockWithShowMore text={JSON.stringify(l)} />
<TouchableOpacity onPress={() => remove(i)}>
<TextBlockWithShowMore text="remove" />
</TouchableOpacity>
<Input onChange={c => update(i, c.nativeEvent.text, "name")} />
</React.Fragment>
))}
</>
);
};

Text field should only change for one value and not over the entire list

I have a list and this list has several elements and I iterate over the list. For each list I display two buttons and an input field.
Now I have the following problem: as soon as I write something in a text field, the same value is also entered in the other text fields. However, I only want to change a value in one text field, so the others should not receive this value.
How can I make it so that one text field is for one element and when I write something in this text field, it is not for all the other elements as well?
import React, { useState, useEffect } from 'react'
import axios from 'axios'
function Training({ teamid }) {
const [isTrainingExisting, setIsTrainingExisting] = useState(false);
const [trainingData, setTrainingData] = useState([]);
const [addTraining, setAddTraining] = useState(false);
const [day, setDay] = useState('');
const [from, setFrom] = useState('');
const [until, setUntil] = useState('');
const getTrainingData = () => {
axios
.get(`${process.env.REACT_APP_API_URL}/team/team_training-${teamid}`,
)
.then((res) => {
if (res.status === 200) {
if (typeof res.data !== 'undefined' && res.data.length > 0) {
// the array is defined and has at least one element
setIsTrainingExisting(true)
setTrainingData(res.data)
}
else {
setIsTrainingExisting(false)
}
}
})
.catch((error) => {
//console.log(error);
});
}
useEffect(() => {
getTrainingData();
}, []);
const deleteTraining = (id) => {
axios
.delete(`${process.env.REACT_APP_API_URL}/team/delete/team_training-${teamid}`,
{ data: { trainingsid: `${id}` } })
.then((res) => {
if (res.status === 200) {
var myArray = trainingData.filter(function (obj) {
return obj.trainingsid !== id;
});
//console.log(myArray)
setTrainingData(() => [...myArray]);
}
})
.catch((error) => {
console.log(error);
});
}
const addNewTraining = () => {
setAddTraining(true);
}
const addTrainingNew = () => {
axios
.post(`${process.env.REACT_APP_API_URL}/team/add/team_training-${teamid}`,
{ von: `${from}`, bis: `${until}`, tag: `${day}` })
.then((res) => {
if (res.status === 200) {
setAddTraining(false)
const newTraining = {
trainingsid: res.data,
mannschaftsid: teamid,
von: `${from}`,
bis: `${until}`,
tag: `${day}`
}
setTrainingData(() => [...trainingData, newTraining]);
//console.log(trainingData)
}
})
.catch((error) => {
console.log(error);
});
}
const [editing, setEditing] = useState(null);
const editingTraining = (id) => {
//console.log(id)
setEditing(id);
};
const updateTraining = (trainingsid) => {
}
return (
<div>
{trainingData.map((d, i) => (
<div key={i}>
Trainingszeiten
<input class="input is-normal" type="text" key={ d.trainingsid } value={day} placeholder="Wochentag" onChange={event => setDay(event.target.value)} readOnly={false}></input>
{d.tag} - {d.von} bis {d.bis} Uhr
<button className="button is-danger" onClick={() => deleteTraining(d.trainingsid)}>Löschen</button>
{editing === d.trainingsid ? (
<button className="button is-success" onClick={() => { editingTraining(null); updateTraining(d.trainingsid); }}>Save</button>
) : (
<button className="button is-info" onClick={() => editingTraining(d.trainingsid)}>Edit</button>
)}
<br />
</div>
))}
)
}
export default Training
The reason you see all fields changing is because when you build the input elements while using .map you are probably assigning the same onChange event and using the same state value to provide the value for the input element.
You should correctly manage this information and isolate the elements from their handlers. There are several ways to efficiently manage this with help of either useReducer or some other paradigm of your choice. I will provide a simple example showing the issue vs no issue with a controlled approach,
This is what I suspect you are doing, and this will show the issue. AS you can see, here I use the val to set the value of <input/> and that happens repeatedly for both the items for which we are building the elements,
const dataSource = [{id: '1', value: 'val1'}, {id: '2', value: 'val2'}]
export default function App() {
const [val, setVal]= useState('');
const onTextChange = (event) => {
setVal(event.target.value);
}
return (
<div className="App">
{dataSource.map(x => {
return (
<div key={x.id}>
<input type="text" value={val} onChange={onTextChange}/>
</div>
)
})}
</div>
);
}
This is how you would go about it.
export default function App() {
const [data, setData]= useState(dataSource);
const onTextChange = (event) => {
const id = String(event.target.dataset.id);
const val = String(event.target.value);
const match = data.find(x => x.id === id);
const updatedItem = {...match, value: val};
if(match && val){
const updatedArrayData = [...data.filter(x => x.id !== id), updatedItem];
const sortedData = updatedArrayData.sort((a, b) => Number(a.id) - Number(b.id));
console.log(sortedData);
setData(sortedData); // sorting to retain order of elements or else they will jump around
}
}
return (
<div className="App">
{data.map(x => {
return (
<div key={x.id}>
<input data-id={x.id} type="text" value={x.value} onChange={onTextChange}/>
</div>
)
})}
</div>
);
}
What im doing here is, finding a way to map an element to its own with the help of an identifier. I have used the data-id attribute for it. I use this value again in the callback to identify the match, update it correctly and update the state again so the re render shows correct values.

React button to show an element

I'm pulling countries from the Restcountries API and if the current state of the array has more than one or less than or equal to ten countries, I want to list the country names along with a 'show' button next to each one. The show button should display what's in the return (render) of my Country function. In the App function, I wrote a handler for the button named handleViewButton. I'm confused on how to filter the element in the Countries function in the else conditional statement in order to display the Country. I tried passing handleViewButton to the Button function, but I get an error 'Uncaught TypeError: newSearch.toLowerCase is not a function'. I really just want to fire the Country function to display the country button that was pressed.
App.js
import React, { useState, useEffect } from 'react';
import './App.css';
import axios from 'axios';
const Country = ({country}) => {
return (
<>
<h2>{country.name}</h2>
<p>capital {country.capital}</p>
<p>population {country.population}</p>
<br/>
<h3>languages</h3>
{country.languages.map(language => <li key={language.name}>{language.name}</li>)}
<br/>
<img src={country.flag} alt="country flag" style={{ width: '250px'}}/>
</>
);
}
const Countries = ({countries, handleViewButton}) => {
const countriesLen = countries.length;
console.log(countriesLen)
if (countriesLen === 0) {
return (
<p>Please try another search...</p>
);
} else if (countriesLen === 1) {
return (
<ul>
{countries.map((country, i) => <Country key={i} countriesLen={countriesLen} country={country}/>)}
</ul>
);
} else if (countriesLen > 10) {
return (
<div>
<p>Too many matches, specify another filter</p>
</div>
);
} else {
return (
<ul>
{countries.map((country, i) => <li key={i}>{country.name}<Button handleViewButton={handleViewButton}/></li>)}
</ul>
)
};
};
const Button = ({handleViewButton}) => {
return (
<button onClick={handleViewButton}>Show</button>
);
};
const Input = ({newSearch, handleSearch}) => {
return (
<div>
find countries <input value={newSearch} onChange={handleSearch}/>
</div>
);
};
function App() {
const [countries, setCountries] = useState([]);
const [newSearch, setNewSearch] = useState('');
const handleSearch = (event) => {
const search = event.target.value;
setNewSearch(search);
};
const handleViewButton = (event) => {
const search = event.target.value;
setNewSearch(countries.filter(country => country === search));
};
const showCountrySearch = newSearch
? countries.filter(country => country.name.toLowerCase().includes(newSearch.toLowerCase()))
: countries;
useEffect(() => {
axios
.get('https://restcountries.eu/rest/v2/all')
.then(res => {
setCountries(res.data);
console.log('Countries array loaded');
})
.catch(error => {
console.log('Error: ', error);
})
}, []);
return (
<div>
<Input newSearch={newSearch} handleSearch={handleSearch}/>
<Countries countries={showCountrySearch} handleViewButton={handleViewButton}/>
</div>
);
};
export default App;
you can use a displayCountry to handle the country that should be displayed. Most often you would use an id, but I'm using here country.name since it should be unique.
Then you would use matchedCountry to find against your list of countries.
After that, a onHandleSelectCountry to select a given country. if it's already selected then you could set to null to unselect.
Finally, you would render conditionally your matchedCountry:
const Countries = ({countries}) => {
const [displayCountry, setDisplayCountry] = useState(null);
const countriesLen = countries.length;
const matchedCountry = countries.find(({ name }) => name === displayCountry);
const onHandleSelectCountry = (country) => {
setDisplayCountry(selected => {
return selected !== country.name ? country.name : null
})
}
if (countriesLen === 0) {
return (
<p>Please try another search...</p>
);
} else if (countriesLen === 1) {
return (
<ul>
{countries.map((country, i) => <Country key={i} countriesLen={countriesLen} country={country}/>)}
</ul>
);
} else if (countriesLen > 10) {
return (
<div>
<p>Too many matches, specify another filter</p>
</div>
);
} else {
return (
<>
<ul>
{countries.map((country, i) => <li key={i}>{country.name}<Button handleViewButton={() => onHandleSelectCountry(country)}/></li>)}
</ul>
{ matchedCountry && <Country countriesLen={countriesLen} country={matchedCountry}/> }
</>
)
};
};
I can only help to point out some guidelines.
First: The button does not have value attribute. Hence what you will get from event.target.value is always blank.
const Button = ({handleViewButton}) => {
return (
<button onClick={handleViewButton}>Show</button>
);};
First->Suggestion: Add value to the button, of course you need to pass the value in.
const Button = ({handleViewButton, value}) => {
return (
<button onClick={handleViewButton} value={value}>Show</button>
);};
Second: To your problem 'Uncaught TypeError: newSearch.toLowerCase is not a function'. Filter always returns an array, not a single value. if you do with console or some sandbox [1,2,3].filter(x=>x===2) you will get [2] not 2.
const handleViewButton = (event) => {
const search = event.target.value;
setNewSearch(countries.filter(country => country === search));
};
Second->Suggestion: To change it to get the first element in array, since country(logically) is unique.
const result = countries.filter(country => country === search)
setNewSearch(result.length>0?result[0]:"");
A better approach for array is find, which always return first result and as a value. E.g. [1,2,2,3].find(x=>x===2) you will get 2 not [2,2] or [2].
countries.find(country => country === search)

react-table, useState hook within table results to default value although set before

I am using react-table to display fetched data within a table. You also have different buttons within that table to interact with the data such as deleting an entry, or updating its data (toggle button to approve a submitted row).
The data is being fetched in an initial useEffect(() => fetchBars(), []) and then being passed to useTable by passing it through useMemo as suggested in the react-table documentation. Now I can click on the previously mentioned buttons within the table to delete an entry but when I try to access the data (bars) that has been set within fetchBars()it returns the default state used by useState() which is an empty array []. What detail am I missing? I want to use the bars state in order to filter deleted rows for example and thus make the table reactive, without having to re-fetch on every update.
When calling console.log(bars) within updateMyData() it displays the fetched data correctly, however calling console.log(bars) within handleApprovedUpdate() yields to the empty array, why so? Do I need to pass the handleApprovedUpdate() into the cell as well as the useTable hook as well?
const EditableCell = ({
value: initialValue,
row: { index },
column: { id },
row: row,
updateMyData, // This is a custom function that we supplied to our table instance
}: CellValues) => {
const [value, setValue] = useState(initialValue)
const onChange = (e: any) => {
setValue(e.target.value)
}
const onBlur = () => {
updateMyData(index, id, value)
}
useEffect(() => {
setValue(initialValue)
}, [initialValue])
return <EditableInput value={value} onChange={onChange} onBlur={onBlur} />
}
const Dashboard: FC<IProps> = (props) => {
const [bars, setBars] = useState<Bar[]>([])
const [loading, setLoading] = useState(false)
const COLUMNS: any = [
{
Header: () => null,
id: 'approver',
disableSortBy: true,
Cell: (props :any) => {
return (
<input
id="approved"
name="approved"
type="checkbox"
checked={props.cell.row.original.is_approved}
onChange={() => handleApprovedUpdate(props.cell.row.original.id)}
/>
)
}
}
];
const defaultColumn = React.useMemo(
() => ({
Filter: DefaultColumnFilter,
Cell: EditableCell,
}), [])
const updateMyData = (rowIndex: any, columnId: any, value: any) => {
let barUpdate;
setBars(old =>
old.map((row, index) => {
if (index === rowIndex) {
barUpdate = {
...old[rowIndex],
[columnId]: value,
}
return barUpdate;
}
return row
})
)
if(barUpdate) updateBar(barUpdate)
}
const columns = useMemo(() => COLUMNS, []);
const data = useMemo(() => bars, [bars]);
const tableInstance = useTable({
columns: columns,
data: data,
initialState: {
},
defaultColumn,
updateMyData
}, useFilters, useSortBy, useExpanded );
const fetchBars = () => {
axios
.get("/api/allbars",
{
headers: {
Authorization: "Bearer " + localStorage.getItem("token")
}
}, )
.then(response => {
setBars(response.data)
})
.catch(() => {
});
};
useEffect(() => {
fetchBars()
}, []);
const handleApprovedUpdate = (barId: number): void => {
const approvedUrl = `/api/bar/approved?id=${barId}`
setLoading(true)
axios
.put(
approvedUrl, {},
{
headers: {Authorization: "Bearer " + localStorage.getItem("token")}
}
)
.then(() => {
const updatedBar: Bar | undefined = bars.find(bar => bar.id === barId);
if(updatedBar == null) {
setLoading(false)
return;
}
updatedBar.is_approved = !updatedBar?.is_approved
setBars(bars.map(bar => (bar.id === barId ? updatedBar : bar)))
setLoading(false)
})
.catch((error) => {
setLoading(false)
renderToast(error.response.request.responseText);
});
};
const renderTable = () => {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = tableInstance;
return(
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
<span {...column.getSortByToggleProps()}>
{column.render('Header')}
</span>{' '}
<span>
{column.isSorted ? column.isSortedDesc ? ' ▼' : ' ▲' : ''}
</span>
<div>{column.canFilter ? column.render('Filter') : <Spacer/>}</div>
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row)
const rowProps = {...row.getRowProps()}
delete rowProps.role;
return (
<React.Fragment {...rowProps}>
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
)
})}
</tr>
{row.isExpanded ? renderRowSubComponent({row}): null}
</React.Fragment>
)})
}
</tbody>
</table>
)
}
}
export default Dashboard;
You're seeing stale values within handleApprovedUpdate because it's capturing bars the first time the component is rendered, then never being updated since you're using it inside COLUMNS, which is wrapped with a useMemo with an empty dependencies array.
This is difficult to visualize in your example because it's filtered through a few layers of indirection, so here's a contrived example:
function MyComponent() {
const [bars, setBars] = useState([]);
const logBars = () => {
console.log(bars);
};
const memoizedLogBars = useMemo(() => logBars, []);
useEffect(() => {
setBars([1, 2, 3]);
}, []);
return (
<button onClick={memoizedLogBars}>
Click me!
</button>
);
}
Clicking the button will always log [], even though bars is immediately updated inside the useEffect to [1, 2, 3]. When you memoize logBars with useMemo and an empty dependencies array, you're telling React "use the value of bars you can currently see, it will never change (I promise)".
You can resolve this by adding bars to the dependency array for useMemo.
const memoizedLogBars = useMemo(() => logBars, [bars]);
Now, clicking the button should correctly log the most recent value of bars.
In your component, you should be able to resolve your issue by changing columns to
const columns = useMemo(() => COLUMNS, [bars]);
You can read more about stale values in hooks here. You may also want to consider adding eslint-plugin-react-hooks to your project setup so you can identify issues like this automatically.

How to handle socket callbacks that dispatches to redux sequentially too much and blocks the app? react-redux batch?

In our app, there are some data updates coming via sockets.
In the callbacks of the socket a redux action is dispatched.
Here is an example
const onReceiveLocationMessages = function(message) {
let payload = JSON.parse(message.body);
console.log("received locations", payload);
dispatch(onLocationChange(payload));
};
Now occasionally a lot of updates come through socket at once, thus the callback is fired sequentially, so many dispatches are fired as well. This results in app lagging like navigating, opening menus, clicking buttons etc. because as I guess a lot of renders are happening.
I guess something similar to batch https://react-redux.js.org/api/batch from react-redux would help here. But as the example shows there it combines multiple dispatches at once, and in this case, it's quick sequential dispatches.
So what's the best practice to handle these kinds of situations?
Are you sure you are not needlessly rendering many parts of your application or having a long running reducer that causes the lag? If you're using pure components with reselect you can prevent components from rendering needlessly and get a less laggy app.
Below is an example of a helper function named createBatchAction that does batched updates. You pass the action creator (toggleColorBatched) to the helper and a batchPeriod parameter and will return a new action creator thunk that will run all the collected actions within the batch period.
There is another action creator named toggleColorNotBatched that is dispatched together with batchedToggleColorBatche (new thunk action created with createBatchAction) but you can see that the batched version updates DOM in batches.
const {
Provider,
useDispatch,
useSelector,
batch,
} = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;
// helper to batch action
const createBatchAction = (actionCreator, batchPeriod) => {
const data = { dispatch: null, actions: [] };
setInterval(() => {
batch(() =>
data.actions.forEach((action) => data.dispatch(action))
);
data.actions = [];
}, batchPeriod);
return (...args) => (dispatch) => {
data.dispatch = dispatch;
data.actions.push(actionCreator(...args));
};
};
const ROWS = 10;
const COLS = 20;
const BLUE = 'blue';
const RED = 'red';
const initial = Array(ROWS)
.fill()
.map(() =>
Array(COLS)
.fill()
.map(() => ({ color: BLUE }))
);
const initialState = {
batched: initial,
notBatched: initial,
};
const nextItem = ((row, col) => () => {
col += 1;
if (col >= COLS) {
col = 0;
row += 1;
}
if (row >= ROWS) {
row = 0;
}
return { row, col };
})(0, -1);
//action types
const TOGGLE_COLOR_BATHCED = 'TOGGLE_COLOR_BATHCED';
const TOGGLE_COLOR_NOT_BATCHED = 'TOGGLE_COLOR_NOT_BATCHED';
//action creators
const toggleColorBatched = ({ row, col }) => ({
type: TOGGLE_COLOR_BATHCED,
payload: { row, col },
});
const toggleColorNotBatched = ({ row, col }) => ({
type: TOGGLE_COLOR_NOT_BATCHED,
payload: { row, col },
});
//batched version of toggleColor that batches all actions every second
const batchedToggleColorBatche = createBatchAction(
toggleColorBatched,
1000
);
const setToggle = (rows, row, col) =>
rows.map((val, i) =>
i === row
? val.map((val, i) =>
i === col
? {
...val,
color: val.color === BLUE ? RED : BLUE,
}
: val
)
: val
);
const reducer = (state, { type, payload }) => {
if (type === TOGGLE_COLOR_BATHCED) {
const { row, col } = payload;
return {
...state,
batched: setToggle(state.batched, row, col),
};
}
if (type === TOGGLE_COLOR_NOT_BATCHED) {
const { row, col } = payload;
return {
...state,
notBatched: setToggle(state.notBatched, row, col),
};
}
return state;
};
//selectors
const selectBatched = (state) => state.batched;
const selectNotBatched = (state) => state.notBatched;
//creating store with redux dev tools
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducer,
initialState,
composeEnhancers(
applyMiddleware(
//adding thunk like middleware
({ dispatch, getState }) => (next) => (action) =>
typeof action === 'function'
? action(dispatch, getState)
: next(action)
)
)
);
// Col only re renders if props passed to it change
const Col = React.memo(function Col({ col }) {
return <td style={{ color: col.color }}>X</td>;
});
// Row only re renders if props passed to it change
const Row = React.memo(function Row({ row }) {
return (
<tr>
{row.map((col, i) => (
<Col key={i} col={col} />
))}
</tr>
);
});
const App = () => {
const batched = useSelector(selectBatched);
const notBatched = useSelector(selectNotBatched);
const dispatch = useDispatch();
React.useEffect(() => {
const interval = setInterval(() => {
const item = nextItem();
dispatch(batchedToggleColorBatche(item));
dispatch(toggleColorNotBatched(item));
}, 50);
const item = nextItem();
dispatch(batchedToggleColorBatche(item));
dispatch(toggleColorNotBatched(item));
return () => clearInterval(interval);
}, [dispatch]);
return (
<table>
<tbody>
<tr>
<td>
<h1>batched</h1>
</td>
<td>
<h1>not batched</h1>
</td>
</tr>
<tr>
<td>
<table>
<tbody>
{batched.map((row, i) => (
<Row key={i} row={row} />
))}
</tbody>
</table>
</td>
<td>
<table>
<tbody>
{notBatched.map((row, i) => (
<Row key={i} row={row} />
))}
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
);
};
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>
<div id="root"></div>

Resources