React Components - I-3138
React Components - I-3138
Components in React
A component is a small, reusable chuck of code. It lets you split the UI into
independent, reusable pieces, and think about each piece in isolation.
Create and Maintain state information Create and Maintain state information
with hooks with lifecycle methods
Do not require the render function Require a render function that returns
an HTML element
The typical folder structure in a React project can follow the following conventions to
make the code more organised.
Example Snapshot -
Components
This folder consists of a collection of reusable UI components like buttons, modals,
inputs, loader, etc. They can be used across various files in the project.
Pages
The files in the pages folder indicate the route of the react application. Each file in
this folder corresponds to a standalone page of the project.
Utils
Utils folder consists of some repeatedly used functions that are commonly used in
the project.
State in React
State is a built-in object in React that is used to contain dynamic information about a
component. Unlike props that are passed from the outside, a component maintains
its own state.
A component's state is mutable and it can change over time. Whenever it changes,
the component re-renders.
Super
The super keyword calls the constructor of the parent class. In our case the call to
super passes the props argument to the constructor of React.Component class and
saves the return value for the derived class component.
Anytime that we call this.setState it automatically calls the render method as soon as
the state changes which rerenders the component with the updated state value.
Accessing previous state values
The setState method can take a callback function as an argument which receives
the previous state as a default parameter. This is useful in cases where we need
access to previous state values to update the current state.
State is Asynchronous
The setState method works in an asynchronous way. That means after calling
setState the this.state variable is not immediately changed.
So If we want to perform an action after the state value is updated we can pass a
callback function as a second parameter to the setState method.
Example snippet -
import { Component } from "react";
export default class Navbar extends Component {
constructor(props) {
super(props);
// initialising state
this.state = { count: 0 };
}
// access previous state with a callback
updateState = () => {
this.setState((prev) => ({ count: prev.count + 1 }));
};
render() {
return (
<div>
<h1>Count is {this.state.count}</h1>
<button onClick={this.updateState}>Click Me</button>
</div>
);
}
}
Some References:
❖ Function and Class Components: link