0
\$\begingroup\$

I'm new to react and I'm still using the life cycle methods, so my question is sincecomponentDidMount() acts like a constructor I'm planning to initialize everything there:

render() {        return (            <div className="done-container" style={this.style().taskContainer}>                <span style={this.style().title}>Done</span>                {                    this.props.done.map((d) => (                    <div className={`done ${this.state.isActive ? 'active' : ''}`} id={this.props.done.id}                    onClick={(e) => {                        this.props.setTaskID(d.id);                        this.setToActive(e); //3.Call <-----                        this.props.arrowStyleToDone();                    }}>                    </div>                    ))                }            </div>        )    }    setToActive  //1.Declare <----    componentDidMount() {        //2.Initialize  <-----        this.setToActive = (e) => {            if(!e.target.classList.contains('active')) {                e.currentTarget.classList.add('active');                e.currentTarget.classList.add('border-done')                this.props.closeAllTasks();                this.props.closeAllDoing();            } else {                e.currentTarget.classList.remove('active');                e.currentTarget.classList.remove('border-done')                this.props.disableArrowButton();            }        }    }}

My idea is that if I declare everything inside the class which looks very ugly in my opinion, but then initializing everything oncomponentDidMount() my web app will be faster because it won't need to declare and initialize everything every render.

Is this correct? and should I put the declaring and initialization on top ofrender()? but thecomponenDidMount() is called after the initial render.

askedFeb 3, 2020 at 15:42
Kevin Bryan's user avatar
\$\endgroup\$
1
  • \$\begingroup\$Can I suggest reducing your indent size.\$\endgroup\$CommentedFeb 4, 2020 at 0:41

1 Answer1

1
\$\begingroup\$

Lifecycle hooks are functions that are invoked at different stages of a component. Hereconstructor() andcomponentDidMount() works different. From my point of view,state variables are initialized insideconstructor() and api calls are done incomponentDidMount() hook. we are not supposed to define function definitions inside lifecycle hooks. Your above component can be converted to

class Demo extends React.Component {  constructor(props) {    super(props);    this.state = {      isActive: false    };  }  setToActive = (e, id) => {    const {      setTaskID,      arrowStyleToDone,      closeAllTasks,      closeAllDoing,      disableArrowButton    } = this.props;    setTaskID(id);    arrowStyleToDone();    if (!e.target.classList.contains("active")) {      e.currentTarget.classList.add("active");      e.currentTarget.classList.add("border-done");      closeAllTasks();      closeAllDoing();    } else {      e.currentTarget.classList.remove("active");      e.currentTarget.classList.remove("border-done");      disableArrowButton();    }  };  componentDidMount() {} // no need for this lifecycle since we are not making any initial function call, like fetch from api etc.  render() {    const { done } = this.props;    const { isActive } = this.state;    return (      <div className="done-container" style={this.style().taskContainer}>        <span style={this.style().title}>Done</span>        {done &&          done.map(item => (            <div              className={`done ${isActive ? "active" : ""}`}              key={item.id}              onClick={e => this.setToActive(e, item.id)}            ></div>          ))}      </div>    );  }}

Basic structure of React component is

Class component

class Class_Name extends Component{    constructor(){      this.state = {} // state variable      this.toggleTab = this.toggleTab.bind(this);    }   // other functions   toggleTab = ()=>{} // these are example functions.   // life cycle hooks if you are using any   render(){    return (    )   }}
answeredFeb 3, 2020 at 15:59
Akhil Aravind's user avatar
\$\endgroup\$
2
  • \$\begingroup\$thank you, I guess I'm just going to use componentDidMount() for http requests, then define functions in the class but outside the render().\$\endgroup\$CommentedFeb 4, 2020 at 2:38
  • \$\begingroup\$@KevinBryan exactly thats how you do, you can reach me at anytime. will update if I am free\$\endgroup\$CommentedFeb 4, 2020 at 3:55

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.