Browse Courses

Passing Data Between Components

This document explains how data and state are passed between React components covering lifecycle phases, parent-child communication, and callback usage for effective state management.

This document explores how React components manage and exchange data and state, detailing the component lifecycle phases, parent-child and child-parent communication patterns, and practical examples for robust state management in modern React applications.


React Component Lifecycle and Data Flow

React components have three main lifecycle phases: mounting, updating, and unmounting. Each phase involves specific methods that control how components are created, updated, and removed from the DOM.

Lifecycle Phases

PhaseDescription
MountingComponent is created and inserted into the DOM
UpdatingComponent re-renders due to state or prop changes
UnmountingComponent is removed from the DOM

Mounting Methods

  • constructor: Initializes the component and state, may call super(props).
  • getDerivedStateFromProps: Syncs state with props if needed.
  • render: Returns the JSX for the UI (must return a single root element).
  • componentDidMount: Runs after the component is mounted; often used for data fetching or subscriptions.

Updating Methods

  • getDerivedStateFromProps: Called before every render if props change.
  • shouldComponentUpdate: Determines if a re-render is needed (returns true by default).
  • render: Updates the UI based on new state/props.
  • getSnapshotBeforeUpdate: Captures information from the DOM before changes are applied.
  • componentDidUpdate: Runs after updates are flushed to the DOM.

Unmounting Method

  • componentWillUnmount: Used for cleanup (e.g., removing timers or listeners).

Passing Data Between Components

Data can be passed between React components in several ways, depending on their relationship.

Parent to Child (Using Props)

The parent component passes data to the child via props. When the parent updates the prop values, the child receives the new data and re-renders.

 1// Parent Component
 2class App extends React.Component {
 3  state = { name: 'John', color: 'green' }
 4  render() {
 5    return <AppInner name={this.state.name} color={this.state.color} />
 6  }
 7}
 8
 9// Child Component
10class AppInner extends React.Component {
11  render() {
12    return <div style={{ color: this.props.color }}>{this.props.name}</div>
13  }
14}

Child to Parent (Using Callbacks)

The parent passes a callback function to the child as a prop. The child calls this function to send data back to the parent.

 1// Parent Component
 2class App extends React.Component {
 3  state = { time: '' }
 4  setTime = currentTime => {
 5    this.setState({ time: currentTime })
 6  }
 7  render() {
 8    return <AppInner parentCallback={this.setTime} />
 9  }
10}
11
12// Child Component
13class AppInner extends React.Component {
14  componentDidMount() {
15    setInterval(() => {
16      const now = new Date().toLocaleTimeString()
17      this.props.parentCallback(now)
18    }, 1000)
19  }
20  render() {
21    return <div>Sending time to parent...</div>
22  }
23}

Comparison of Data Passing Methods

RelationshipMethodExample Mechanism
Parent to ChildProps<Child prop=value />
Child to ParentCallback PropparentCallback(data)
Sibling to SiblingState ManagerRedux, Context API

Conclusion

React components manage their own state and communicate through props and callbacks. Understanding the lifecycle phases and data flow patterns is essential for building robust, maintainable React applications.


FAQ

  1. By using props to send values from parent to child
  2. By directly modifying the child’s state
  3. By using Redux only
  4. By calling the child’s render method
(1) By using props to send values from parent to child

The component may leave behind timers or event listeners, causing memory leaks or unexpected behavior after it is removed from the DOM.

  1. getDerivedStateFromProps is called before every render if props change
  2. shouldComponentUpdate determines if a re-render is needed
  3. getSnapshotBeforeUpdate is called after the DOM updates
  4. componentDidUpdate runs after updates are flushed to the DOM
(3) getSnapshotBeforeUpdate is called before the DOM updates, not after.

Callbacks allow child components to send data or trigger actions in the parent by invoking functions passed as props.

MethodUse Case
A. Props1. Parent to child communication
B. Callback Prop2. Child to parent communication
C. Redux3. Sibling to sibling sharing
D. State4. Local component data
A-1, B-2, C-3, D-4.

Overriding shouldComponentUpdate incorrectly can prevent necessary re-renders or cause performance issues by allowing unnecessary updates.

When the parent needs to receive data or be notified of events occurring in the child, such as form submissions or timer updates.

Ensure the parent is passing the correct props and that the child’s render method uses those props properly.

Data can only be passed from parent to child in React, not from child to parent.

False. Data can be passed from child to parent using callback functions.

  1. Using props for parent-to-child
  2. Using callback props for child-to-parent
  3. Using Redux or Context for siblings
  4. Directly modifying another component’s state
(4) Directly modifying another component’s state is not valid in React.