Reputation: 112887
I have a MobX observable array, and I want to remove multiple elements with lodash's remove. This causes a re-render for every element in the array.
const array = observable([1,2,3,4,5,1]);
const App = observer(() => {
console.log('Rendering...');
return (
<div>
{ array.map(e => <div> {e} </div>)}
</div>
);
});
ReactDOM.render(
<App />,
document.getElementById('app')
);
If I try to remove every occurrence of 1
, Rendering...
is logged once for every element:
_.remove(array, num => num === 1);
> "Rendering..."
> "Rendering..."
> "Rendering..."
> "Rendering..."
> "Rendering..."
> "Rendering..."
How can I make it so it just re-renders once?
Upvotes: 1
Views: 544
Reputation: 112887
The API to MobX looks just like vanilla JavaScript, but every alteration of the observable array causes a synchronous update of all observers. One way to mitigate this is to put the code in a runInAction:
runInAction(() => _.remove(array, num => num === 1));
> "Rendering..."
Upvotes: 5