Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New To React Hook useState Is Returning Undefined

useState() is giving me undefined to the new state variable (notifications):

const Notifications = (props) => {
    const [notifications, setNotifications] = useState(props.notifications);//notifications = undefined, props = {notifications: Array(0)}
    useEffect(() => {
        if (props.notifications) {
        setNotifications(props.notifications);
        }
    }, [props.notifications]);
    // do stuff....

I am expecting notifications to be [] and then subsequently update it with setNotifications() when props.notifications changes. props.notification is coming from a redux store. I don't know if this changes anything but i did set an initial State.

const initialState = Immutable.fromJS({
  notifications: [],
});

Don't know why i am getting undefined...

Edit: Got rid of typo and testing code

like image 641
RhinoBomb Avatar asked Apr 08 '19 04:04

RhinoBomb


1 Answers

To set initial state properly you should pass it to the useState as an argument, so:

const [notifications, setNotifications] = useState([]);

Also no matter if you set props.notifications outside somewhere or not, but if you rely on it having some kind of default value in the component, then you should set it right there, e.g.:

const Notifications = ({ notifications = [] }) => {

And the last but not the least, using array in dependency list of useEffect has some unwanted side-effects, for example if notifications structuruly will stay the same (same items, same length), but will be a new array, useEffect will miss a cache, since it only does a shallow comparison. Consider using a hashing function of some kind instead of the array itself (e.g. JSON.stringify)

like image 113
jayarjo Avatar answered Oct 07 '22 23:10

jayarjo