Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Setting component state using a function outside of state, is it wrong?

Is it wrong to use setState in a function outside of the React component?

Example:

// myFunction.js
function myFunction() {
  ...
  this.setState({ ... })
}

// App.js
import myFunction from './myFunction

class App extends Component {
  constructor() {
    super()
    this.myFunction = myFunction.bind(this)
  }

  ...
}
like image 368
corasan Avatar asked Sep 01 '25 02:09

corasan


2 Answers

I'm not sure the way you're binding will actually work. You could do something like:

export const getName = (klass) => {
  klass.setState({ name: 'Colin'})
}

then

class App extends Component {
  state = {
    name: 'React'
  };

  handleClick = () => {
    getName(this);
  }

  render() {
    return (
      <div>
        <p>{this.state.name}</p>
        <button onClick={this.handleClick}>change name</button>
      </div>
    );
  }
}

Working example here.

like image 51
Colin Ricardo Avatar answered Sep 02 '25 17:09

Colin Ricardo


So the only reasons to do this is if you are reducing repeated code, e.g. two components use the same logic before calling this.setState, or if you want to make testing easier by having a separate pure function to test. For this reason I recommend not calling this.setState in your outside function, but rather returning the object you need so it can you can call this.setState on it.

function calculateSomeState(data) {
  // ...
  return { updated: data };
}

class MyComponent extends React.Component {
    constructor(props) {
      super(props)
      this.state = calculateSomeState(props.data);
    }

    handleChange = (e) => {
        const value = e.target.value;
        this.setState(calculateSomeState({ ...props.data, value }));
    }
}
like image 38
Ryan Castner Avatar answered Sep 02 '25 15:09

Ryan Castner