React components -(Class component v/s function component)
Manikandan K
Posted on February 1, 2024
What is a Component?
- Component is independent and reusable bits of code.
- Components let you break up the user interface into separate pieces / that can then be reused / and handled independently.
Class Component v/s Function Component
Class Component :
- To define a React component / as a class, extend the built-in Component class / and define a render method.
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
- To use Lifecycle methods in class Components.
- Little complex compared with Functional Components.
Class component without state
Class component with state
Function Component :
- React functional component is a simple JavaScript function / that accepts props and returns a React element.
- These functions may or may not receive data as parameters.
// Normal function
function Welcome () {
return <h1>Hello, {this.props.name}</h1>;
}
//Arrow function
const Welcome = () => {
return <h1>Hello, {this.props.name}</h1>;
}
- Function components are called stateless components (Before Introducing hook).
- Access state and other react features (lifecycle methods) using hooks.
- Easy to create Function components.
function component without state
function component with state
💖 💪 🙅 🚩
Manikandan K
Posted on February 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.