YouTip LogoYouTip

React Component Api

React Component API involves several important aspects, including lifecycle methods, state management, property passing, and event handling. Here is a detailed explanation of the React Component API: ## Lifecycle Methods The lifecycle methods of a React component are divided into three main phases: mounting, updating, and unmounting. For detailed information, see: (#). ### Mounting Phase * `constructor(props)`: A constructor used to initialize state or bind methods. * `static getDerivedStateFromProps(props, state)`: Called before each render method to update state. * `componentDidMount()`: Called after the component is mounted. DOM operations or data requests can be performed here. ## Example class MyComponent extends React.Component{ constructor(props){ super(props); this.state={ count:0}; } static getDerivedStateFromProps(nextProps, prevState){ if(nextProps.reset){ return{ count:0}; } return null; } componentDidMount(){ console.log('Component mounted'); } render(){ return
{this.state.count}
; } } ### Updating Phase * `static getDerivedStateFromProps(props, state)`: Same as in the mounting phase, used to update state. * `shouldComponentUpdate(nextProps, nextState)`: Returns a boolean value to determine whether the component should re-render. * `render()`: Renders the component's UI. * `getSnapshotBeforeUpdate(prevProps, prevState)`: Called before the DOM is updated to capture some information (e.g., scroll position). * `componentDidUpdate(prevProps, prevState, snapshot)`: Called after the component is updated. ## Example class MyComponent extends React.Component{ shouldComponentUpdate(nextProps, nextState){ return nextState.count!==this.state.count; } getSnapshotBeforeUpdate(prevProps, prevState){ return{ scrollPosition: window.scrollY}; } componentDidUpdate(prevProps, prevState, snapshot){ if(snapshot){ window.scrollTo(0, snapshot.scrollPosition); } console.log('Component updated'); } render(){ return
{this.state.count}
; } } ### Unmounting Phase * `componentWillUnmount()`: Called just before the component is unmounted, used to clean up resources (e.g., timers, event listeners). ## Example class MyComponent extends React.Component{ componentWillUnmount(){ console.log('Component will unmount'); } render(){ return
{this.state.count}
; } } * * * ## State Management State is internal data of a component, defined and managed using `this.state`. State is updated via the `setState` method. ## Example class MyComponent extends React.Component{ constructor(props){ super(props); this.state={ count:0}; } increment =()=>{ this.setState((prevState)=>({ count: prevState.count+1})); }; render(){ return(

Count:{this.state.count}

); } } ## Property Passing Access properties passed to the component via `this.props`. Type checking can be performed using PropTypes. ## Example import PropTypes from 'prop-types'; class MyComponent extends React.Component{ render(){ return
{this.props.title}
; } } MyComponent.propTypes={ title: PropTypes.string.isRequired, }; // Using the component and passing properties ## Event Handling Handle user interactions through event handler functions. Use `.bind(this)` or arrow functions to ensure the correct `this` context. ## Example class MyComponent extends React.Component{ handleClick =()=>{ console.log('Button clicked'); }; render(){ return; } } ## Conditional Rendering Control the rendering of components through conditional statements. ## Example class MyComponent extends React.Component{ constructor(props){ super(props); this.state={ isVisible:true}; } toggleVisibility =()=>{ this.setState((prevState)=>({ isVisible:!prevState.isVisible})); }; render(){ return(
{this.state.isVisible&&

This is visible

}
); } } ## List Rendering Render lists using the array's `map` method. ## Example class MyComponent extends React.Component{ render(){ const items =['Item 1','Item 2','Item 3']; return(
    {items.map((item, index)=>(
  • {item}
  • ))}
); } } ## Controlled Components Control the values of form elements through state. ## Example class MyComponent extends React.Component{ constructor(props){ super(props); this.state={ value:''}; } handleChange =(event)=>{ this.setState({ value: event.target.value}); }; handleSubmit =(event)=>{ event.preventDefault(); console.log('Submitted value:',this.state.value); }; render(){ return( ); } } * * * ## Setting State: setState `setState` is the method used in React to update the component's state. The syntax is as follows: setState(object nextState[, function callback]) ### Parameter Description * `object nextState`: An object containing the key-value pairs of the state to be updated. React will merge this object into the current state. * `function callback`: An optional callback function that will be executed after the state has been updated and the component has re-rendered. Merges `nextState` with the current state and re-renders the component. `setState` is the primary method for triggering UI updates in React event handler functions and request callback functions. ### About setState You cannot modify the state directly within the component using `this.state`, as this state will be replaced after `setState()` is called. `setState()` does not immediately change `this.state`; instead, it creates a state that will be processed. `setState()` is not necessarily synchronous; React batches state and DOM rendering to improve performance. `setState()` will always trigger a component redraw, unless some conditional rendering logic is implemented in `shouldComponentUpdate()`. By using `setState` appropriately, you can effectively manage component state and ensure that necessary operations are performed after the state is updated, thereby improving the responsiveness and reliability of the application. ## React Example class Counter extends React.Component{constructor(props){super(props); this.state = {clickCount: 0}; this.handleClick = this.handleClick.bind(this); }handleClick(){this.setState(function(state){return{clickCount: state.clickCount + 1}; }); }render(){return(

Click me! Click count: {this.state.clickCount}

); }}const root = ReactDOM.createRoot(document.getElementById("root")); root.render(); [Try it Β»](#) In the example, clicking the h2 tag increments the click counter by 1.
← React Component ApiReact State β†’