The react hook equivalent to the old componentWillReceive props can be done using the useEffect hook, just specifying the prop that we want to listen for changes in the dependency array.

I.e:

export default (props) => {

    useEffect( () => {
        console.log('counter updated');
    }, [props.counter])

    return <div>Hi {props.counter}</div>
}

For componentDidUpdate just by omitting the dependency array, the useEffect function will be called after every re-render.

I.e:

export default (props) => {

    useEffect( () => {
        console.log('counter updated');
    })

    return <div>Hi {props.counter}</div>
}
Answer from fgonzalez on Stack Overflow
🌐
GitHub
gist.github.com › WrathChaos › c476aac7c102ea2f01fd955c05b685f8
React Hooks: componentWillReceiveProps · GitHub
// Class componentWillReceiveProps(nextProps) { if (nextProps.data !== this.props.data) { console.log('Prop Received: ', nextProps.data); } } // React Hooks: componentWillReceiveProps useEffect(() => { console.log('Prop Received: ', props.data); }, [props.data])
🌐
DEV Community
dev.to › dance_nguyen › nextjs-getstaticprops-getserversideprops-useeffect-47jo
Next.js: getStaticProps, getServerSideProps, useEffect??? - DEV Community
May 30, 2025 - It's a lifecycle method that activates whenever your component rerenders, based on the criteria you pass it. Think of an app that refetches new data based on a user clicking a button; useEffect can wait for that click then do a new fetch.
Discussions

componentWillReceiveProps, componentDidUpdate for React Hook
I run into two challenges: Even if, as per React guideline, derived state is discouraged, but some edge cases still need it. In terms of a functional component with React Hook, What is the equival... More on stackoverflow.com
🌐 stackoverflow.com
why should I not use use state and useEffect on next?
What the hell? Where is this from that’s an odd take!! I’d love to read this in full More on reddit.com
🌐 r/nextjs
95
62
August 31, 2023
getStaticProps or useEffect | for fetching data from the API
getStaticProps is used when your page is being built during 'build' mode. Its great to use as it pages the page faster by statically providing all necessary data to the component. You can access all the data fetched by getStaticProps into your Component by pushing data into props key returned by getStaticProps, and use the said data from the props of the Component itself There would be no need for lazy-loading as the data would already exist and wont cause a delay. But it is necessary to remember getStaticProps runs only once, (i.e. during build time) if you wanr your function to run on each reload of page, either use getInitialProps or useSWR hook and next/dynamic More on reddit.com
🌐 r/nextjs
5
8
September 6, 2021
Useeffect and serversideprops
serversideprops are running on a backend only. Useeffect hook for a clientside only. More on reddit.com
🌐 r/nextjs
10
4
August 27, 2022
🌐
DEV Community
dev.to › alexandprivate › nextprops-in-react-functional-components-1jc2
Compare Props in React Functional Components. - DEV Community
April 29, 2021 - componentWillReceiveProps(nextProps) { if(nextProps.count !== this.props.count) { // Do something here since count prop has a new value } } So let's say you need to do something like this in React 17 today, to skip an apollo query or to avoid any kinda side effects inside your components? The first thing that may cross your mind is to set some states inside your component to track the props values using a useEffect hook: function ComponentGettingProps({count, ...restProps}) { const [localCount, setLocalCount] = React.useState(0) React.useEffect(() => { if(count === localCount) { // count prop has the same value setLocalCount(count) // ...
🌐
GitHub
github.com › reactjs › rfcs › issues › 76
[Hooks] useEffect hook api advice · Issue #76 · reactjs/rfcs
October 29, 2018 - prevProps: it should leave the comparing logic to us rather than the second param of useEffect even though the second param of useEffect is calculated by us in the SFC. If the element is just constructed, prevProps is null; nextProps: we need param nextProps to decide what should we do.
🌐
LogRocket
blog.logrocket.com › home › how to access previous props or state with react hooks
How to access previous props or state with React Hooks - LogRocket Blog
June 4, 2024 - Learn how to access previous props and state in React using useRef, useState, usePrevious, and useEffect hooks effectively.
🌐
Reddit
reddit.com › r/nextjs › why should i not use use state and useeffect on next?
r/nextjs on Reddit: why should I not use use state and useEffect on next?
August 31, 2023 - I think they mean in the context of initial data fetching? It's normal to do useEffect and uses tate when a component first loads to fetch data, but with Next and React 18, it's better to use server side fetching and suspense.
Find elsewhere
🌐
DhiWise
dhiwise.com › post › nextjs-useeffect-guide-for-managing-side-effects
Next.js useEffect for Effective Side Effect Management
June 7, 2024 - When fetching data in Next.js, prefer server-side methods like getStaticProps or getServerSideProps for initial data population. Use useEffect for client-side data fetching when necessary, such as when data changes based on user interaction.
🌐
Reddit
reddit.com › r/nextjs › getstaticprops or useeffect | for fetching data from the api
r/nextjs on Reddit: getStaticProps or useEffect | for fetching data from the API
September 6, 2021 -

So I was building a website in the nextjs. and I want to fetch some data from the API. but now I'm confused that should I use the useEffect hook in the component itself or use the getStaticProps on the page!!!

using the useEffect is easy we have the current component access and all but,
there are so many questions while using getStaticProps like:

  1. Can I do error handling in it?

  2. Can I show page loading?

  3. If I don't use it and use useEffect instead, will it be good?

  4. Can I store data in redux store from it?

  5. There could be more questions to that depending on the conditions...

I mean I can run that and test them and I know that if I pass the data to the component from the getStaticProps, it will work, or at least it should. but again will there be a right way to do those things.

So if anyone can help it would be very kind 😇
THANX

Top answer
1 of 2
5
getStaticProps is used when your page is being built during 'build' mode. Its great to use as it pages the page faster by statically providing all necessary data to the component. You can access all the data fetched by getStaticProps into your Component by pushing data into props key returned by getStaticProps, and use the said data from the props of the Component itself There would be no need for lazy-loading as the data would already exist and wont cause a delay. But it is necessary to remember getStaticProps runs only once, (i.e. during build time) if you wanr your function to run on each reload of page, either use getInitialProps or useSWR hook and next/dynamic
2 of 2
4
Hi u/alg002 , I think it will depend on how you want to render the content of your pages: client-side rendering or pre-rendering. By default, React does client-side rendering with useEffect. Next.js does static rendering with getStaticProps. The difference is when your data is fetched. With you useEffect(), the data is fetched when the component renders on the page (hence the need for loaders or spinners), whereas with getStaticProps(), the data is fetched at build time and is cached so that when a user visits your page, they're served the code with the data already fetched (this is faster). I recommend choosing your data fetching method depending on the purpose of your page. For example, is it a marketing page with static information? Is it a product or blog page? Is it an interactive dashboard? If your data changes frequently, you might want to consider ou might want to fetch data on the client-side with useEffect or useSWR . If your data is static but might change regurlarly, you might want to consider Incremental Static Regenaration , etc. I hope this helps, please let us know if you have any follow-up questions!
🌐
React
react.dev › reference › react › Component
Component – React
UNSAFE_componentWillReceiveProps does not mean that the component has received different props than the last time. You need to compare nextProps and this.props yourself to check if something changed.
🌐
Stack Overflow
stackoverflow.com › questions › 65134661 › nextjs-useeffect-triggers-every-time-i-route
NextJs useEffect triggers every time I route
A useEffect will run every time a component remounts. Which is fine, except that you are unconditionally fetching in the callback you give it.
🌐
Upmostly
upmostly.com › home › next.js › a developer's guide to using useeffect
A Developer's Guide to Using useEffect in Next.js - Upmostly
May 25, 2023 - Here’s a possible example where you might want to have no dependencies in your useEffect array. In this case we have our imaginary social media, but now we’re taking in the user as a prop, and then fetching the friends list for our user in our component.
Top answer
1 of 1
1

Yes man, this is possible but using NextJs you'll lose the server side rendering feature, in this case I recommend you to do something like Override the getServerSideProps function and add the session validation into it since nextJs Server side have access to cookies and session.

This is an example of what you could do:

withSSRAuth.ts (file)

import { GetServerSideProps, GetServerSidePropsContext, GetServerSidePropsResult } from 'next';
import {
  getSession,
} from 'next-auth/client';
import { destroyCookie, parseCookies } from 'nookies';
import { AuthTokenError } from 'services/errors/AuthTokenError';

export function withSSRAuth<P>(fn: GetServerSideProps<P>): GetServerSideProps {
  return async (ctx: GetServerSidePropsContext): Promise<GetServerSidePropsResult<P>> => {
    const session = await getSession(ctx);
    const cookies = parseCookies(ctx);
    const { 'uberPlantao.user': savedUser } = cookies;

    if (!session && !savedUser) {
      return {
        redirect: {
          destination: '/',
          permanent: false,
        },
      };
    }
    try {
      return await fn(ctx);
    } catch (err) {
      if (err instanceof AuthTokenError) {
        destroyCookie(ctx, 'uberPlantao.user');
        destroyCookie(ctx, 'uberPlantao.token');
        destroyCookie(ctx, 'uberPlantao.refreshToken');

        return {
          redirect: {
            destination: '/',
            permanent: false,
          },
        };
      }
      return err;
    }
  };
}

Then use it as your getServerSideProps (when you want to validate the session into some page)

page index.tsx (session validation is required)

import Image from 'next/image';
import { useRef, useCallback } from 'react';
import { FiUser, FiLock } from 'react-icons/fi';

import { useRouter } from 'next/router';

import { Form } from '@unform/web';
import { FormHandles } from '@unform/core';
import { toast } from 'react-toastify';
import * as Yup from 'yup';

import getValidationErrors from 'utils/getValidationErrors';
import { withSSRAuth } from 'utils/withSSRAuth';

import { Button } from 'components/Atoms/Button';
import { FbButton } from 'components/Atoms/FbButton';
import { Input } from 'components/Atoms/Input';
import { Seo } from 'components/Atoms/Seo';
import { Separator } from 'components/Atoms/Separator';

import {
  Container, LogoContainer, FormContainer, ButtonsContainer, Footer,
} from 'styles/pages/index';
import { useAuth } from 'hooks/auth';

type DataFormInfo = {
  email: string;
  password: string;
}

const Home = (): JSX.Element => {
  const formRef = useRef<FormHandles>(null);

  const { push } = useRouter();
  const { signInWithFacebook, isLoading, defaultSignIn } = useAuth();

  const handleFbLogin = async (): Promise<void> => {
    signInWithFacebook();
  };

  const handleLogin = useCallback(
    async (data: DataFormInfo) => {
      console.log('login');
    },
    [defaultSignIn, push],
  );

  return (
    <Container>
      <Seo title="Home | Uber de plantões" metaDesc="Created by thl dev" />
      <LogoContainer>
      </LogoContainer>
      <FormContainer>
        <Form ref={formRef} onSubmit={handleLogin} autoComplete="off">
        </Form>
      </FormContainer>
      <Separator className="sep" type="horizontal" customWidth={40} />
      <Footer>
      </Footer>
    </Container>
  );
};

export default Home;

export const getServerSideProps = withSSRAuth(async () => ({
  props: {},
}));

Every time that you use withSSRAuth as a wrapper of your getServerSideProps it'll validate if there's some user into cookies (you can use session too but in my case I've used cookies)

If there's no user it'll redirect to some url that you can chose into destination.

This way to validate a session isn't the best one but it prevents your page from flickering while checking if there's some user via client side

🌐
Stack Overflow
stackoverflow.com › questions › 65194774 › how-to-call-getserversideprops-with-useeffect-in-next-js
reactjs - How to call getServerSideprops with useEffect in Next.js - Stack Overflow
December 8, 2020 - In order words, when FindstayFilter component renders, useEffect hook inside A, B, C, D, E, F rerender the component total 6 times which triggers calling getServerSideProps 6 times as well.
🌐
React
react.dev › reference › react › useEffect
useEffect – React
useEffect is a Hook, so you can only call it at the top level of your component or your own Hooks. You can’t call it inside loops or conditions.
🌐
Stack Overflow
stackoverflow.com › questions › 68741431 › what-is-nextprops-in-unsafe-componentwillreceiveprops-and-convert-it-into-react
reactjs - What is nextprops in UNSAFE_componentWillReceiveProps and convert it into React Hook Functional component? - Stack Overflow
UNSAFE_componentWillReceiveProps(nextProps) { let oldGroupList = (this.props.contentMultiaction && this.props.contentMultiaction.groups) || []; let newGroupList = nextProps.contentMultiaction?.groups || []; if (oldGroupList.length !== newGroupList.length) { this.getShownGroups(nextProps); } this.checkAllGroupsState(nextProps); } Though this is a deprecated life cycle method, I wanted to knw how to rewrite it in functional component. Thanks in advance ... Use useEffect() hook.
🌐
GitHub
github.com › vercel › next.js › discussions › 15126
Please need Help!! How to correctly use getInitialProps and useEffect simultaneously? · vercel/next.js · Discussion #15126
July 13, 2020 - So using NextJs's getInitialProps I fetch the list of Products and pass it on to the components and it works. There is a requirement, whenever a city changes(from Dropdown) in client-side, I need to refetch the updated list from the server, So I have this API call in a useEffect.
Author   vercel