skip to Main Content

My useEffect is not firing at all:

import React, { useEffect } from 'react'

function Home(props) {    

    useEffect = (() => {
        onPageLoad()
    }, [])

    const onPageLoad = () => {
        console.log('hello from page load')
    }    

    return (        
        <p>Home Component</p>       
    )
}

export default Home

I’m stumped on this. There’s nothing in the console.

4

Answers


  1. There should be something some error at least in the developer console in the browser, since it seems you have written a syntax error. You are currently trying to assign a new value to the imported variable useEffect but I believe you may have meant to call the function instead:

    import React, { useEffect } from 'react'
    
    function Home(props) {    
    
        useEffect(() => {
            onPageLoad()
        }, [])
    
        const onPageLoad = () => {
            console.log('hello from page load')
        }    
    
        return (        
            <p>Home Component</p>       
        )
    }
    
    export default Home
    
    Login or Signup to reply.
  2. UPDATE

    Just noticed this, your useEffect function is read-only. Notice the = sign after useEffect. Hence, the function might not be getting called.

    useEffect = (() => {
        onPageLoad()
    }, [])
    

    Instead, can you please try something like mentioned below.
    Also, I suggest try declaring the onPageLoad function outside of the component.

    import { useEffect } from "react";
    
    const onPageLoad = () => {
      console.log("hello from page load");
    };
    
    const Home = (props) => {
      useEffect(() => {
        onPageLoad();
      }, []);
    
      return <p>Home Component</p>;
    };
    
    export default Home;
    
    Login or Signup to reply.
  3. There is a syntax error (Error: "useEffect" is read-only) in your code. Please have a look at more details about the Error: useEffect read-only.

    It should be like this:

      useEffect(() => {
        onPageLoad();
      }, []);
    

    Instead of this:

        useEffect = (() => {
            onPageLoad()
        }, [])
    

    Please have a look at the working CodeSandbox example.

    Login or Signup to reply.
  4. if you want fire onPageLoad for each navigate use loc=useLocation() and loc.path as dependencies useEffect .

    const onPageLoad=()=>{
    alert('hello'); // use alert for better trace
    }
    const loc=useLocation();
    React.useEffect(onPageLoad,[loc.pathname]) 
    

    also please declare and then use-it . one Clouse function is enough

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search