243

I'm expecting state to reload on props change, but this does not work and user variable is not updated on next useState call, what is wrong?

function Avatar(props) {
  const [user, setUser] = React.useState({...props.user});
  return user.avatar ? 
         (<img src={user.avatar}/>)
        : (<p>Loading...</p>);
}

codepen

1
  • 2
    Is that all the code in the component or it's shortened for simplicity? As it is, it makes no sense to use an intermediate state instead of simply props.user.
    – tokland
    Jan 30, 2022 at 20:22

7 Answers 7

437

The argument passed to useState is the initial state much like setting state in constructor for a class component and isn't used to update the state on re-render

If you want to update state on prop change, make use of useEffect hook

function Avatar(props) {
  const [user, setUser] = React.useState({...props.user});

  React.useEffect(() => {
      setUser(props.user);
  }, [props.user])

  return user.avatar ? 
         (<img src={user.avatar}/>)
        : (<p>Loading...</p>);
}

Working demo

14
  • 62
    When setting initial state in constructor its clear to understand that constructor is called once on class instance creation. With hooks it looks like useState is called each time on function call and each time it should initialize state, but some unexplained "magic" happen there.
    – vitalyster
    Feb 25, 2019 at 12:31
  • 1
    if you need to merge props into state, you get stuck in an infinite loop when using create-react-app which requires state to be in the dependency array
    – user210757
    Jul 29, 2019 at 16:42
  • 4
    This ends up setting the initial state twice which is pretty annoying. I wonder if you can set the initial state to null and then use React.useEffect to set the initial state at each time. Aug 13, 2019 at 5:08
  • 9
    This doesn't work if state is also controlling rendering. I have a functional component that renders based on props and renders based on state. If the state tells the component to render because it changed, then the useEffect runs and sets state back to the default value. This is really bad design on their part.
    – Greg Veres
    Feb 9, 2020 at 2:56
  • 2
    @igorsantos07 The state only sets back to props value changes if the props.user changes and not otherwise Apr 28, 2020 at 8:48
71

I've seen almost all the answers to this question promoting a bad pattern: updating state as a result of a prop change inside a useEffect call. The useEffect hook is used for synchronizing your React components with external systems. Using it for synchronizing React states can potentially lead to bugs (because re-renders caused by other effects can lead to unintended state updates). A better solution would be to trigger a reconciliation with a key prop change in the <Avatar /> component from its parent:

// App.jsx
function App() {
   // ...logic here
   return <Avatar initialUser={user} key={user.id} />
}

// Avatar.jsx
function Avatar({ initialUser }) {
 // I suppose you need this component to manage it's own state 
 // otherwise you can get rid of this useState altogether.
  const [user, setUser] = React.useState(initialUser);
  return user.avatar ? (
    <img src={user.avatar} />
  ) : (
    <p>Loading...</p>
  );
}

You can think of that key prop in this case as the dependency array of useEffect, but you won't be triggering unintended state changes as a result of unexpected useEffect calls triggered by the component renders.

You can read more about this here: Putting Props To State

And more info on how useEffect might be a foot gun, here:

You Might Not Need an Effect

7
  • 7
    Thank you! "You Might Not Need an Effect" is a gem!
    – jlh
    Jul 9, 2022 at 14:09
  • Upvoted. This approach is good if you have a specific key for child. I tried enabling Chrome Paint Flash, noticed green rectangles for full child, not just the changed element. I feel like going back to useEffect. Aug 16, 2022 at 11:17
  • I would say that if you have measured performance and it drastically affects the rendering behavior, you may consider opting in for some optimizations like memoization via React.memo (there's also 'conditionally rendering' or 'lifting up the state' as mentioned in the "Putting props to State" article). I'm not sure that trading possible UI inconsistencies for a slight win on performance is a good tradeoff. I've found out that useEffect is where most of the times violations of idempotence occur, so I feel like this wave of "avoiding useEffect as much as you can" is the right path forward. Aug 17, 2022 at 16:55
  • 1
    Thank you! Helped me solve an issue I have been having for hours Mar 10 at 22:58
  • Actually I change the way to use key but it still not working
    – huykon225
    Apr 12 at 4:01
21

Functional components where we use useState to set initial values to our variable, if we pass initial value through props, it will always set same initial value until you don't make use of useEffect hook,

for example your case this will do your job

 React.useEffect(() => {
      setUser(props.user);
  }, [props.user])

The function passed to useEffect will run after the render is committed to the screen.

By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.

React.useEffect(FunctionYouWantToRunAfterEveryRender)

if you pass only one argument to useEffect it will run this method after every render you can decide when to fire this FunctionYouWantToRunAfterEveryRender by passing second argument to useEffect

React.useEffect(FunctionYouWantToRunAfterEveryRender, [props.user])

as you notice i am passing [props.user] now useEffect will only fire this FunctionYouWantToRunAfterEveryRender function when props.user is changed

i hope this helps your understanding let me know if any improvements are required thanks

9

you can create your own custom simple hooks for this. The hooks changed default value when it changed.

https://gist.github.com/mahmut-gundogdu/193ad830be31807ee4e232a05aeec1d8

    import {useEffect, useState} from 'react';

    export function useStateWithDep(defaultValue: any) {
      const [value, setValue] = useState(defaultValue);
    
      useEffect(() => {
        setValue(defaultValue);
      }, [defaultValue]);
      return [value, setValue];
    }

#Example

const [user, setUser] = useStateWithDep(props.user);
2
  • 1
    Let's improve the types: function useStateWithDep<T>(defaultValue: T), return [value, setValue] as const.
    – tokland
    Jan 30, 2022 at 20:16
  • Not that useful because useEffect callback will be called after the return statement. So at first it'll return old values. Jun 19, 2022 at 8:54
4

I've created custom hooks like this:

const usePrevious = value => {
   const ref = React.useRef();

   React.useEffect(() => {
       ref.current = value;
   }, [value]);

   return ref.current;
}

const usePropState = datas => {
    const [dataset, setDataset] = useState(datas);
    const prevDatas = usePrevious(datas);

    const handleChangeDataset = data => setDataset(data);

    React.useEffect(() => {
        if (!deepEqual(datas, prevDatas)) // deepEqual is my function to compare object/array using deep-equal
            setDataset(datas);
    }, [datas, prevDatas]);

    return [
        dataset,
        handleChangeDataset
    ]
}

To use:

const [state, setState] = usePropState(props.datas);
1
  • 1
    why are you creating an unstable (not using useCallback) handleChangeDataset instead of returning the stable setDataset instead?
    – philk
    May 9, 2022 at 22:16
2

The parameter passed to React.useState() is only the initial value for that state. React isn't going to recognize that as changing the state, only setting its default value. You'll want to set the default state initially, and then conditionally call setUser(newValue), which will be recognized as a new state, and re-render the component.

I would recommend caution updating state without some kind of condition to keep it from constantly updating, and therefore re-rendering everytime props are received. You may want to consider hoisting the state functionality to a parent component and passing the state of the parent down to this Avatar as a prop.

-4

According to the ReactJS documentation about Hooks :

But what happens if the friend prop changes while the component is on the screen? Our component would continue displaying the online status of a different friend. This is a bug. We would also cause a memory leak or crash when unmounting since the unsubscribe call would use the wrong friend ID.

Your only interaction here should happen on a props change, which seems not to work. You could (still according to the doc) use a componentDidUpdate(prevProps) to proactively catch any update to the props.

PS : I don't have enough code to judge, but couldn't you actively setUser() inside your Avatar(props) function ?

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.