0

So I have a simple application here

const storageKey = 'loggedBlogAppUser';

const loadUser = () => JSON.parse(localStorage.getItem(storageKey));

const App = () => {
  const [blogs, setBlogs] = useState([]);
  const [user, setUser] = useState(null);
  const [newBlog, setNewBlog] = useState('');

  useEffect(() => {
    blogService.getAll().then((b) => setBlogs(b));
  }, []);

  useEffect(() => {
    const loggedUser = storage.loadUser();
    setUser(loggedUser);
    console.log(`loggedUser`, loggedUser);
    console.log(`user`, user);
  }, []);

But in my console my log statements are

loggedUser {token: "..."}

user null

Why does my user log result in null. I called setUser as loggedUser and the loggedUser log actually has content. Shouldn't they refer to the same object?

  • `user` will only have the new value the *next* time the component renders. Since you are passing an empty dependency list to `useEffect`, that callback will only be called the *first* time the component renders. A call to `setUser` cannot magically update `user` in the same render pass. – Felix Kling May 01 '21 at 22:14
  • In React, state updates are asynchronously handled, between render cycles, so when logging state you can only ever log the value from the ***current*** render cycle, not what you just enqueued for the ***next*** render cycle. If you want to log state updates then use an `useEffect` with dependency on *that* state. – Drew Reese May 01 '21 at 22:18

0 Answers0