1

I have exploring reactjs and noticed the two way of defining elemens/components.

class Welcome extends React.Component {
  render() {
      return <h1>Hello, {this.props.name}</h1>;    
  };
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

And the functional approach :

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

They are are identical in terms of results. But functional appracoh is much more cleaner for me at least.

What brings the classing approach: From reactjs documentation:

This lets us use additional features such as local state and lifecycle hooks.

Is there any more advantages beside states, life cycle hooks of classing over pure functional approach?

When to use which one?

1
  • First approach is more like other OO languages and cleaner to use. You can try making complex components using both method and see which one is cleaner Commented May 29, 2017 at 18:34

1 Answer 1

2

Is there any more advantages beside states, life cycle hooks of classing over pure functional approach?

No.

When to use which one?

You have to use classes if you need the additional functionality they provide(*). Otherwise is more a matter of personal preference.


*: For example, lifecycle methods let you implement logic to avoid rerendering a component which can be important for performance.

Sign up to request clarification or add additional context in comments.

5 Comments

Hi thanks for the answer. I have also noticed that I had to write render() in class approach while in functional approach I just returned the template. Is there any reason?
A class is a basically a collection of properties/methods. It cannot directly contain executable code. So the render code must be contained inside a method and it so happens that the method name is render. How else would you do it?
Thanks for the extension of your answer. I was just not sure why there are two methods and how to decide which one to use.
This might help to understand why/when local state and lifecycle methods are useful: facebook.github.io/react/docs/state-and-lifecycle.html
Thanks. I am going through to them and playing. Since it is a new syntax (JSX) I have to go through several times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.