Tim von Känel
Tim von Känel

Reputation: 43

React functional component doesnt rerender when changing props passed as an array

My functional Component doesn't rerender when i pass an array as it's props and change the values of the array.

https://codesandbox.io/s/5ym4vkrnnk

or

import React, { PureComponent, Fragment } from "react";
import ReactDOM from "react-dom";

const SomeFunctionalComponent = props => {
  return <span>{props.array[0]}</span>;
};

class App extends PureComponent {
  state = {
    array: [1, 2, 3]
  };
  increase = () => {
    var array = this.state.array;
    array[0] = array[0] + 1;
    this.setState({ array: array });
    console.log(this.state.array);
  };
  render() {
    return (
      <Fragment>
        <button onClick={this.increase}>Increase</button>
        <SomeFunctionalComponent array={this.state.array} />
      </Fragment>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

My questions:

  1. Why is that so?
  2. How can i change that?

Thanks for any help in advance!

Upvotes: 1

Views: 1297

Answers (1)

aravind_reddy
aravind_reddy

Reputation: 5486

Never Mutate the state directly

you are mutating the state directly in your code so the changes are not getting reflected. Array becomes a reference to this.state.array, which causes the undesired mutation.

import React, { PureComponent, Fragment } from "react";
import ReactDOM from "react-dom";

const SomeFunctionalComponent = props => {
  return <span>{props.array[0]}</span>;
};

class App extends PureComponent {
  state = {
    array: [1, 2, 3]
  };
  increase = () => {
    var array = [...this.state.array];
    array[0] = array[0] + 1;
    this.setState({ array: array });
    console.log(this.state.array);
  };
  render() {
    return (
      <Fragment>
        <button onClick={this.increase}>Increase</button>
        <SomeFunctionalComponent array={this.state.array} />
      </Fragment>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Upvotes: 3

Related Questions