+ 2

Can anyone help me with the travel of data from one life-cycle method to another life-cycle method in react.js

Hi all ! In react.js we use class based components and functional components. In the class based components we use the life-cycle methods. In the life-cycle methods we pass data from one life-cycle method to another. I undestand the flow of how the life-cycle methods run one after the other but I'm unable to pass the data from one method to other. Can any one help me with this? Thank you.

27th Jul 2020, 4:13 AM
Aditya
Aditya - avatar
1 ответ
+ 1
Hi Aditya, For both the Class and Functional components, you need to make use of the state to share data between the lifecycle methods. Consider an app that refreshes the time for every 1 second. For a Class Component: // Class Component start import React from "react"; class Time extends React.Component { state = { time: new Date(), }; componentDidMount() { setInterval(() => { this.setState({ time: new Date() }); }, 1000); } render() { let time = this.state.time ? this.state.time.toString() : ""; return ( <div> <p>The time is: {time}</p> </div> ); } } export default Time; // Class Component end For a Functional Component: // Functional Component start import React, { useState, useEffect } from "react"; import "./styles.css"; export default function App() { let [time, setTime] = useState(new Date()); // Similar to componentDidMount useEffect(() => { setInterval(() => { setTime(new Date()); }, 1000); }); return ( <div> <p>The time is: {time ? time.toString() : ""}</p> </div> ); } // Functional Component end
31st Jul 2020, 5:39 AM
Sai Kishore
Sai Kishore - avatar