How do I get cookies in react js using react-cookie?

Amber Normand picture Amber Normand · Apr 5, 2018 · Viewed 8k times · Source

The react-cookie docs have this example

import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import NameForm from './NameForm';
class App extends Component {
  static propTypes = {
    cookies: instanceOf(Cookies).isRequired
  };

  componentWillMount() {
    const { cookies } = this.props;

    this.state = {
      name: cookies.get('name') || 'Ben'
    };
  }

  handleNameChange(name) {
    const { cookies } = this.props;

    cookies.set('name', name, { path: '/' });
    this.setState({ name });
  }

Can I use cookies.get without using componentWillMount?

Answer

Jimi Pajala picture Jimi Pajala · Apr 5, 2018

There is a little miss use of life-cycle hooks there.

You should be giving initial value to state on class constructor.

e.g.

class Example extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      name: this.props.cookies.get('name') || 'Ben',
    }
  }
...

or if you use newer ES7 syntax just

class Example extends React.Component {
    state = {
      name: this.props.cookies.get('name') || 'Ben',
    }
...

constructor -function is not required on lower example

componentWillMount life-cycle will also be deprecated in upcoming React releases so I would recommend to avoid using it.

Replacement for it is accordingly

static getDerivedStateFromProps(nextProps, prevState){
   return {username: nextProps.username}
}

See difference here, we return normal Object which then get's passed to Components state. So in here username would be get passed to state.