react lifecycle hooks in functional components code example

Example 1: how to use componentdidmount in functional component

// passing an empty array as second argument triggers the callback in useEffect
// only after the initial render thus replicating `componentDidMount` lifecycle behaviour
useEffect(() => {
  if(!props.fetched) {
 	 props.fetchRules();
  }
  console.log('mount it!');
}, []);

// componentDidUpdate
useEffect({
	your code here
}) 

// For componentDidUpdate
useEffect(() => {
  // Your code here
}, [yourDependency]);

// For componentWillUnmount
useEffect(() => {
  // componentWillUnmount
  return () => {
     // Your code here
  }
}, [yourDependency]);

Example 2: react lifecycle hooks

class Content extends React.Component {
  // ...
  componentWillMount() {
    this.setState({ activities: data });
  }
  // ...
}

Example 3: components react to hooks

import React, { useState } from 'react';
function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
  return (
    

You clicked {count} times

); }

Example 4: react lifecycle hooks

class ActivityItem extends React.Component {
  render() {
    const { activity } = this.props;

    return (
      
avatar
{moment(activity.created_at).fromNow()}

{activity.actor.display_login} {activity.payload.action}

{activity.repo.name}
) } }

Tags:

Misc Example