score:0

as @ybrodsky said, you should rather pass down a function which does mutate the state. here is an example:

class app extends component {
  constructor() {
    super();
    this.state = {
      name: 'react'
    };
    this.update=this.update.bind(this);
  }

  update(nextstate) {
    this.setstate(nextstate);
  }

  render() {
    return (
      <child updateparent={this.update} />
    );
  }
}

const child = ({updateparent}) => (
  <button onclick={() => updateparent({name: 'foo bar'})}>click</button>
);

you now have full control over the state of the parent in the child. just pass the object to be shallowly merged into the parent state. in this example, name in app will change to foo bar on button click.

score:0

i guess in functional components its possible to send your setstate to childrens and change parent state in them but not in class base components

score:2

you shouldn't pass the setstate directly, as the setstate function will not change the state immediately.

as the documents said:

think of setstate() as a request rather than an immediate command to update the component. for better perceived performance, react may delay it, and then update several components in a single pass. react does not guarantee that the state changes are applied immediately.

setstate() does not always immediately update the component. it may batch or defer the update until later. so you'd better to manage the calling of setstate function together as there may have competing of mutating parent's state. it is not recommended to pass this function to another component.

encapsulating the calling of setstate function in one class makes your code stronger.

score:5

but this is simple than passing function.if i want change many state change. this will be simple and faster way compare to passing function right ?

the correct way to do this is as simple as yours and does not violate best practices:

class app extends component {
  state = {
      name: 'react',
  };

  render() {
    return (
      <div>
        <hello name={this.state.name} />
        <p>
          start editing to see some magic happen :)
        </p>
        <child onclick={() => this.setstate({name: 'viswa'})}/>
      </div>
    );
  }
}

const child=({onclick})=>(
    <button onclick={onclick}>click</button>
);

Related Query

More Query from same tag