1

There's a React component which its state is an array of svg elements. In each update only 1 element in this array may change. I want to benefit from wise and fast rendering provided by react. I use the following code to update the state and render.

render: function() {
    return (
        <div>
            <svg width={Common.boardWidth} height={Common.boardHeight}>
                {this.state.grid}
            </svg>
        </div>
    );
}

_setNewState: function(index , newState){
    this.setState(function(state){
        return({
            grid: state.grid[index].splice(index,1,newState)
        });
    });
},

_setNewState is called whenever we receive a new change in the state.

My question :

1.How can I replace an element in the array state to still benefit from fast rendering of React ? Do I benefit from fast rendering of react in the current approach ? or as the array changes, the whole thing will be rendered again ? even those elements which didn't change ?

2.What is the best approach in this case ? do we need to have an array of states instead of state that is an array ?

Note: Each element in this array is a SVG element with a unique key.

1 Answer 1

1

You can easily benefit from efficient rendering if you refactor your code a bit so that each SVG element gets a unique key. This key allows the diffing algorithm to determine if the component is the same. Elements which didn't change won't be rerendered on each setState call.

render: function() {
    return (
        <div>
            <svg width={Common.boardWidth} height={Common.boardHeight}>
                {this.state.grid.map(function(svg) {
                     return (<svg key={svg.key} ... the rest of the props/>)                    
                }}
            </svg>
        </div>
    );
}
Sign up to request clarification or add additional context in comments.

4 Comments

Actually, in setInitialState I create the initial array of SVGs with unique keys. And in each subsequent update, only 1 specific SVG element is changed.
then your question is answered isn't it?
Well, you said "refactor your code ..." , I already mentioned in my code what I said in the comment, so I thought maybe you mean something else.... I already have SVG elements with ids.
Yea, you don't have to refactor then, and you're benefitting optimally from Reacts rendering already.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.