Home > front end >  Autocall any function in component where ever it is rendered
Autocall any function in component where ever it is rendered

Time:05-03

I'm new to React JS coding... I would like to know any method to be called in Class-Based Components whenever it gets props and called by another component in their render return methods. Actually! I wanted to run that function every time when that component is being Rendered or Called By another component. I appreciate that...

CodePudding user response:

If I understand correctly you might need a useEffect hook.

useEffect(() => {
    // put code that you want to execute
}, [variable]);

Inside the useEffect put the code you want to execute. In the array you put the variable/s that whenever they change they trigger this useEffect to run. If the array is left empty it will run only at the first render.

For more: https://reactjs.org/docs/hooks-effect.html

CodePudding user response:

In React class components, the render method itself shouldn’t cause side effects. It would be too early — we typically want to perform our effects after React has updated the DOM.

This is why in React classes, we put side effects into componentDidMount and componentDidUpdate. Coming back to our example, here is a React counter class component that updates the document title right after React makes changes to the DOM:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }
  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count   1 })}>
          Click me
        </button>
      </div>
    );
  }
}

we have to duplicate the code between these two lifecycle methods in Classes.

This is because in many cases we want to perform the same side effect regardless of whether the component just mounted, or if it has been updated. Conceptually, we want it to happen after every render — but React class components don’t have a method like this. We could extract a separate method but we would still have to call it in two places.

  • Related