How to use life cycle methods /functions in React Hook?

What's wrong with the following component? Its throws an error while the original class based version with life cycle methods works fine?

import React, { useState, useEffect } from "react";
import axios from "axios";
const  NewsHook = ()=> {
  const [mount, setMount] = useState(false);
  const [news, setNews] = useState([]);
  useEffect(() => {
    setMount(true);
    axios.get('https://hn.algolia.com/api/v1/search?query=react')
        .then(result => {
                if (mount){
                    setNews({
                        news: result.data.hits,
                    })
                }
            }
        );
    return () => {
      setMount(false);
   }
  }, [mount]);

  return (
        <ul>
            {news.map(topic => (
                <li key={topic.objectID}>{topic.title}</li>
            ))}
        </ul>
  );
}
export default NewsHook

the solution was that the following:

setNews(result.data.hits);

Hooks at a Glance – React, Hooks are functions that let you “hook into” React state and lifecycle features from examples comparing useEffect to these methods in Using the Effect Hook.). Add state and lifecycle methods to Function Components with React Hooks. Let’s consider a simple to do list component: Here’s the full code: Nothing new or unusual so far. The component uses componentDidMount lifecycle method to fetch data from a remote source when first rendered and then shows a to do list.

The problem is because the data is fetching. So news will be still null. Either using async to solve the problem or doing in this way :)

import React, { useEffect, useState } from "react";
import axios from "axios";
import "./styles.css";

export default function App() {
  const [mount, setMount] = useState(false);
  const [news, setNews] = useState([{ new: null }]);

  useEffect(() => {
    setMount(true);
    axios
      .get("https://hn.algolia.com/api/v1/search?query=react")
      .then(result => {
        setNews({ new: result.data.hits });
      });

    return () => {
      setMount(false);
    };
  }, [mount]);

  return (
    <div>
      <ul>
        {news.new == null ? (
          <h2>Loading</h2>
        ) : (
          news.new.map(item => {
            return <li key={item.objectID}>{item.title}</li>;
          })
        )}
      </ul>
    </div>
  );
}

it will solve your problem. Hope it is help :)

Replacing Component Lifecycle Methods with React Hooks, Component with a dedicated render function. Since other lifecycle methods will be deprecated in React 17, and, in the interim, require the use of the UNSAFE_ prefix, we will not After (functional component using Hooks):� Then, we looked at the lifecycle methods in React, and how we can use the useEffect Hook to use lifecycle methods in functional components. Full visibility into production React apps Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce.

you don't need to set a state of mount because the useEffect will work automatically when the component mounts and if you want it to work just ones, you add empty array [] as the second argument

and you have to wrap your Axios request inside useEffect to an async function like that:

import React, { useState, useEffect } from "react";
import axios from "axios";

const  NewsHook = ()=> {
  const [news, setNews] = useState([]);

  useEffect(() => {
    const getNews = async () => {
      const result  = await axios.get('https://hn.algolia.com/api/v1/search?query=react');
      setNews({
        news: result.data.hits,
      })
    };
    getNews();
  }, []);

  return (
    <ul>
      {news.map(topic => (
        <li key={topic.objectID}>{topic.title}</li>
       ))}
    </ul>
  );
};

export default NewsHook

Add state and lifecycle methods to Function Components with React , Let's now try to use React Hooks to implement the exact same behaviour in a function component. Imports and component definition. We no� Imitating react life-cycle methods with useEffect hook. some of the life-cycle methods with useEffect hook and hopefully give method is usually used to fire functions that fetch data and

React useEffect : A hook to introduce lifecycle methods in functional , Based on this function, we can use useEffect to replicate one of the major component lifecycles of the class based components. For example: In order to hook into the lifecycle, we'll need to define functions on our component which React calls at the appropriate time for each hook. Let's dive into the first lifecycle hook: componentWillMount () / componentDidMount ()

Lifecycle methods with ReactJS hooks | by Kevin Malazarte, So everyone knows that you can't use lifecycle methods in functional You can see that we are passing a function into our useEffect hook. ReactJS Component Lifecycle Overview: ReactJS Component Lifecycle methods are hooks which are the main part of react framework. ReactJS lifecycle divide mainly into three parts, Mounting, Updating, and Unmounting. In ReactJS, we'll use ES6 (EcmaScript) syntax.

React component lifecycle: React lifecycle methods & hooks, It's all thanks to the useState and useEffect hooks – special functions that hook into React features that allow to set state and use lifecycle� Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes. (We don’t recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you’d like.)

Comments
  • hier is the original class based version with life cycle methods
  • "it throws an error". Please add the error
  • Well. One of the errors I see is the you set news to setNews({news: result.data.hits}) which is news.news[] but when you map the topic you map an object not array of objects. The correct map would be news.news.map()
  • i was not able to post the class based version with only 39 chars which was rejected as too long
  • What error are you getting?
  • Thanks all.The suggested changes do not work. I still get the error: TypeError: news.map is not a function
  • Hi bro, please check the edited answer. I tested it, it should be working