Friday, February 17, 2023

what is side effects and lifecycle in React ?

 In React with TypeScript, a "side effect" refers to any behavior that occurs outside the component's render cycle, such as modifying the DOM, making an API request, or updating a global state.

In functional components, side effects are managed using the useEffect hook. This hook allows you to perform an action when the component mounts, updates, or unmounts. Here's an example of using useEffect to fetch data from an API:



In this example, the useEffect hook is used to make an API request when the component mounts, and updates the data state with the response. The second argument to useEffect is an array of dependencies, which determines when the effect should run. An empty array means it only runs once, when the component mounts.


The "lifecycle" of a component refers to the different stages it goes through from creation to removal. In class components, these stages are defined by a set of lifecycle methods, such as componentDidMount, componentDidUpdate, and componentWillUnmount. In functional components, the useEffect hook is used to manage these stages.


The React component lifecycle can be represented by the following methods:


  • componentDidMount: called once when the component is first mounted
  • componentDidUpdate: called after the component updates (i.e. state or props change)
  • componentWillUnmount: called when the component is about to be removed from the DOM

In functional components, you can use useEffect to perform similar tasks. The useEffect hook can be used to mimic the behavior of all three of the above methods:


  • useEffect(() => { ... }, []) - mimics componentDidMount
  • useEffect(() => { ... }) - mimics componentDidUpdate
  • useEffect(() => { return () => { ... } }) - mimics componentWillUnmount

No comments:

Post a Comment