Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you setState outside of component?

I want to decouple the event handler state change logic from React Component A and put it inside class B. class B (so not a React component) should be able to change state of component A.

So I don't want to pass function reference setState(B.handle) to setState but be able to setState from class B.

How to do it?

Is passing this to constructor of class B the way to go?

edit: sorry, forgot to mention that i can't use third party libraries to keep it dependencies free.

like image 714
J. Reku Avatar asked Feb 04 '26 16:02

J. Reku


2 Answers

The usual way to set state from another component, is through a state engine like redux. When a state gets changed, if multiple components are watching the state, it can update each component that cares about that slice of the application state.

In the latest versions of React, they introduced contexts, which provide similar functionality.

like image 117
ugh StackExchange Avatar answered Feb 06 '26 05:02

ugh StackExchange


I think we can use refs: https://reactjs.org/docs/refs-and-the-dom.html

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  .... // Somewhere
  this.myRef.setState(newState);
  ...
  render() {
   return <ChildComponent ref={this.myRef} />;
  }
}

To make changes to the props: https://facebook.github.io/react-native/docs/direct-manipulation

like image 44
Valeri Avatar answered Feb 06 '26 05:02

Valeri