title: React useState appears null
body: <p>I tried to refactor my class components into functional with hooks, but struggle with initial state declaration.</p>
  <p>Code as follows:</p>
  <pre><code>export default function Profile(){ 
  const [profile, setProfile] = React.useState({
   firstname: '',
   lastname: ''
  })
  
   return (
    &lt;SomeComponent value={profile.firstname} /&gt;
  )
  
  }
  </code></pre>
  <p>Error is &quot;cannot read property 'firstname' of null&quot;</p>
  <p>console.log shows profile.firstname value, though</p>
  <p>I do understand that somehow value is not there yet like with setState, but i don't know how to wait for it, then...
  Because in class components initial state is, well, initialized actually, before render...</p>
  <p>Actual values should be fetched over empty strings after, so it is not the case :/</p>
  <p>Full code, i thought it's too much to copypaste:</p>
  <pre><code>import React, { Component } from 'react'
  import { 
    Container,
    Typography, 
    Paper, 
    Grid, 
    Avatar, 
    IconButton, 
    TextField, 
    Select, 
    InputLabel, 
    NativeSelect } from '@material-ui/core';
  import { makeStyles } from '@material-ui/core/styles';
  import { MuiPickersUtilsProvider, KeyboardDatePicker } from '@material-ui/pickers';
  import DateFnsUtils from '@date-io/date-fns';
  import Skeleton from '@material-ui/lab/Skeleton'
  import jwt_decode from 'jwt-decode'
  import { Redirect } from 'react-router-dom';
  import { useHistory } from 'react-router';
  import { 
    getProfile, 
    getProfileAvatar, 
    editProfile } from '../services/calls'
  import UploadButton from './UploadButton'
  import { 
    CheckCircleIcon,
    CancelIcon,
    EditIcon
    } from '@material-ui/icons';
  import ProfileAvatar from '../components/ProfileAvatar'
  import ProfileDataLine from '../components/ProfileDataLine'
  import { AuthContext } from '../services/AuthContextProvider'
  import { timestring, date_parse } from '../services/suppl'
  
  const useStyles = makeStyles((theme) =&gt; ({
      root: {
        minHeight: 300,
        flexGrow: 1,
        minWidth: 300,
        transform: 'translateZ(0)',
        '@media all and (-ms-high-contrast: none)': {
          display: 'none'},
  
        },
      avatar:{
        width: &quot;100px&quot;,
        height: &quot;100px&quot;,
        'font-size': '1.5em'
      },
      paper: {
        marginTop: theme.spacing(5),
        padding: theme.spacing(3),
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center'
      },
      about: {
        flexDirection: 'column',
        alignItems: 'center'
      },
      edit: {
          'align-self': 'baseline',
          'max-width': 'fit-content',
          'min-width': 'fit-content'
      },
      profilecont: {
        alignItems: 'center',
        justifyContent: 'space-evenly',
      },
      error: {
          color: 'red',
          'font-size': '0.8em'
      },
      message: {
          color: 'green',
          'font-size': '0.8em'
      },
      debug: {
        position: 'fixed',
        top: '120px',
        left: '200px',
        'z-index': '10000',
        'font-size': '1em',
        padding: '0 0',
        margin: '0 0',
        '&amp; &gt; *': {
          'font-size': '0.5em',
          padding: '0 0',
          margin: '0 0'
        }
      }
  
  }));
  
  
  export default function Profile (props) {
      const classes = useStyles();
      const history = useHistory();
      const auth = React.useContext(AuthContext);
    const [profile, setProfile] = React.useState({
        firstname: '',
        lastname: '',
        id: auth.id,
        email: '',
        created: '',
        last_login: '',
        num_logins: '',
        groups_amount: 0,
        students_amount: 0,
        location: 'unknown',
        bday: '',
        pricing: '',
        rights: '' 
    });
      const [edit, setEdit] = React.useState(false);
      const [edited, setEdited] = React.useState(null);
      const [error, setError] = React.useState('');
      const [message, setMessage] = React.useState('');
      const [avatar, setAvatar] = React.useState('');
      const [disabled, setDisabled] = React.useState(false);
  
      const reloader = () =&gt; {
          setAvatar(this.state.avatar+Math.floor(Math.random()*(10**12)))
      }
  
      const profile_loader = () =&gt; {
          if (auth.loggedIn){
              const token = auth.accessToken
              getProfile(profile.id).then(res =&gt; {
                  if (res &amp;&amp; !res.error) {
                      setProfile({
                          ...profile,
                          firstname: res.firstname,
                          lastname: res.lastname,
                          email: res.email,
                          created: res.time_created,
                          last_login: res.last_login ? res.last_login : 'No logins yet',
                          num_logins: res.login_amounts,
                          groups_amount: res.groups_amount,
                          students_amount: res.students_amount,
                          location: res.location ? res.location : 'Unknown',
                          bday: res.bday ? date_parse(res.bday) : 'Unknown',
                          pricing: res.pricing,
                          rights: res.rights
                      })
                      setAvatar(res.avatar_url+Math.floor(Math.random()*(10**12)))
                  }
                  else{
                      history.push(`/users`)
                  }
              })
          }
          else {
              history.push(`/`)
          }
      }
  
  React.useEffect(() =&gt; {
      profile_loader()
    });
  
      const profile_edit = () =&gt; {
          if (auth.loggedIn){
              const token = auth.accessToken
              let user = {id: profile.id}
              const data = edited
              console.log(data)
              const keys = Object.keys(data)
              for (var i = keys.length - 1; i &gt;= 0; i--) {
                  user[keys[i]] = data[keys[i]]
              }
              editProfile(user).then(res =&gt; {
                  if (res &amp;&amp; !res.error) {
                      console.log(res)
                      setMessage('Profile info has been changed', profile_loader())
                  }
                  else {
                      setError(res.error, this.profile_loader())
                  }
              })
          }
          else {
              history.push(`/`) 
          }
      }
  
      const editFields = () =&gt; {
          setEdit(true)
      }
  
      const onChange = e =&gt; {
      e.target.value === '' &amp;&amp; !disabled &amp;&amp; setDisabled(true); setError('fields cannot be emptied');
      e.target.value !== '' &amp;&amp; disabled &amp;&amp; setDisabled(false); setError('');
      setEdited({
          ...edited,
          [e.target.name]: e.target.value
      })
    }
  
      const onDateChange = date =&gt; {
      setEdited({
          ...edited,
          bday: date.toUTCString()
      })
    }
  
    const editFieldsApply = () =&gt; {
      setEdit(false)
      if(!edited){
        setMessage('Nothing changed', setTimeout(() =&gt; setMessage(''), 5000))
      }
      else{
        profile_edit()
        setTimeout(() =&gt; setMessage(''), 5000)
        setTimeout(() =&gt; setError(''), 5000)
      }
    }
  
    const editFieldsCancel = () =&gt; {
      setEdit(false)
      setEdited(null)
    }
  
  
  
      const pricing = (
        profile ?
        profile.pricing === 0 ? 'Demo' :
        profile.pricing === 1 ? 'Basic subscription' : 
        profile.pricing === 2 ? 'Premium subscription' :
        null
        : null
      );
      const rights = (
        profile ?
        profile.rights === 0 ? 'Student' :
        profile.rights === 1 ? 'Teacher' :
        profile.rights === 2 ? 'Administrator' : 
        profile.rights === 3 ? 'Superuser' :
        null
        : null
      );
  
      const now = new Date().getTime()/1000
  
      return (
  profile &amp;&amp; &lt;Container component=&quot;main&quot; maxWidth=&quot;md&quot; spacing={2}&gt;
              &lt;Paper className={classes.paper}&gt;
                &lt;Typography component=&quot;h1&quot; variant=&quot;h6&quot; style={{ marginBottom: '25px' }}&gt;
                Profile ID:{profile.id}
                &lt;/Typography&gt;
                  &lt;Grid container spacing={2} className={classes.profilecont}&gt;
                      &lt;Grid item&gt;
                        &lt;Grid item md={true} sm={true} xs={true} &gt;
                          &lt;IconButton&gt;
                              &lt;ProfileAvatar id={profile.id} avatar={profile.avatar} w='100px' h='100px'/&gt;
                              {profile.id == auth.id &amp;&amp; &lt;UploadButton reloader={() =&gt; {reloader()}} /&gt;}
                          &lt;/IconButton&gt;
                        &lt;/Grid&gt;
                      &lt;/Grid&gt;
                      &lt;Grid item className={classes.about}&gt;
                          &lt;ProfileDataLine editable label='First Name' onChange={onChange} edit={edit} purpose='firstname' value={profile.firstname} new_value={edited.firstname} /&gt;
                          &lt;ProfileDataLine editable label='Last Name' onChange={onChange} edit={edit} purpose='lastname' value={profile.lastname} new_value={edited.lastname} /&gt;
                          &lt;ProfileDataLine editable label='E-Mail' onChange={onChange} edit={edit} purpose='email' value={profile.email} new_value={edited.email} /&gt;
                          &lt;ProfileDataLine label='Created' edit={edit} purpose='created' value={profile.created} /&gt;
                          &lt;ProfileDataLine label='Last login' edit={edit} purpose='last_login' value={profile.last_login} /&gt;
                          &lt;ProfileDataLine label='Num logins' edit={edit} purpose='num_logins' value={profile.num_logins} /&gt;
                          &lt;ProfileDataLine label='Groups' edit={edit} purpose='groups_amount' value={profile.groups_amount} /&gt;
                          &lt;ProfileDataLine label='Students' edit={edit} purpose='students_amount' value={profile.students_amount} /&gt;
                          &lt;ProfileDataLine label='Location' edit={edit} purpose='location' value={profile.location} /&gt;
                          &lt;Grid item md={true} sm={true} xs={true}&gt;
                            {!edit
                            ? profile.bday instanceof Date &amp;&amp; &lt;Typography 
                            id=&quot;bday&quot; 
                            name=&quot;bday&quot; 
                            type=&quot;bday&quot;&gt;
                              Birthday: {timestring(profile.bday).split(' ')[0]}
                            &lt;/Typography&gt;
                            : &lt;MuiPickersUtilsProvider utils={DateFnsUtils}&gt;
                                &lt;KeyboardDatePicker
                                  margin=&quot;normal&quot;
                                  id=&quot;date-picker-dialog&quot;
                                  label=&quot;Choose date&quot;
                                  format=&quot;dd.MM.yyyy&quot;
                                  disableFuture
                                  name='bday'
                                  value={edited.bday != 'Unknown' ? edited.bday : new Date().toISOString().split(' ')[0]}
                                  onChange={onDateChange}
                                  KeyboardButtonProps={{
                                    'aria-label': 'change date',
                                  }}
                                /&gt;
                              &lt;/MuiPickersUtilsProvider&gt;
                            }
                          &lt;/Grid&gt;
                          &lt;ProfileDataLine editable picker edit={edit} new_value={edited.pricing} label='Billing plan' purpose='pricing' value={pricing}/&gt;
                          &lt;ProfileDataLine editable picker edit={edit} new_value={edited.rights} label='Rights' purpose='rights' value={rights}/&gt;
                      &lt;/Grid&gt;
                      &lt;Grid item className={classes.edit} md={true} sm={true} xs={true}&gt;
                                  {auth.loggedIn &amp; auth.exp &gt; now &amp;&amp; auth.id == profile.id
                                      &amp;&amp; &lt;div&gt;
                                          {!edit
                                          ? &lt;IconButton onClick={editFields}&gt;&lt;EditIcon /&gt;&lt;/IconButton&gt;
                                          : &lt;div&gt;
                                              &lt;IconButton onClick={editFieldsApply} disabled={disabled}&gt;&lt;CheckCircleIcon /&gt;&lt;/IconButton&gt;
                                              &lt;IconButton onClick={editFieldsCancel}&gt;&lt;CancelIcon /&gt;&lt;/IconButton&gt;
                                            &lt;/div&gt;
                                          }
                                        &lt;/div&gt;
                                  }
                      &lt;/Grid&gt;
                  &lt;/Grid&gt;          
                &lt;/Paper&gt;
                &lt;Grid container justify=&quot;center&quot; style={{ marginTop: '5px' }}&gt;
                   {error !== '' &amp;&amp; &lt;Typography className={classes.error}&gt;{error}&lt;/Typography&gt;}
                   {message !== '' &amp;&amp; &lt;Typography className={classes.message}&gt;{message}&lt;/Typography&gt;}
                &lt;/Grid&gt;               
  &lt;/Container&gt;
      )
  
  }
  </code></pre>