Hooks

Hooks are functions that let you “hook into” React state and lifecycle features from function components.

useState

function Example() {
  // useState returns a pair: 
  // the current state value and a function that lets you update it.
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
        Click me {count}
    </button>
  );
}

useEffect

function Example() {
  const [count, setCount] = useState(0);
  const [count2, setCount2] = useState(0);

  // This will run at first render and after every component update
  useEffect(() => {
    console.log('changed', count, count2);
    callAPI.addButtonCount(count2);

    // Cleanup mechanism if required
    // This will also run on first render and each time the component updates
    // When the component unmounts it will only call this function
    return () => {
      console.log('Im unhooked');
    };
  });

  return (
    <div>
        <button onClick={() => setCount(count + 1)}>
            Click me {count}
        </button>
        <button onClick={() => setCount2(count2 + 1)}>
            Click me {count}
        </button>
    </div>
  );
}

Props vs State

In a React component, props are variables passed to it by its parent component. State are variables which are directly initialized and managed by the component.

<Comp name="Shane" />

class ChildComponent extends React.Component {
  constructor(props) {
    super(props)
    // Access props
    console.log(props.name);
    // State
    this.state.whatever = 'Whatever'
    // Can also allocate props to internal
    this.state.name = props.name
  }
}

Stateful component

Handles and manipulates state.

class Quote extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      liked: false
    };
  }

  handleLikes() {
    this.setState({
      liked: !this.state.liked
    }
  }

  render() {
    return (
      <div>
        <LikeCounter
          liked={this.state.liked}
          handleLikes={this.handleLikes.bind(this)}
        />
      </div>
    );
  }

Stateless component

Stateless components don't contain any state, they simply render the information, in this case the prop username

export default class Name extends Component {
  render() {
    return (
      <div>
        <h1>{this.props.username}</h1>
      </div>
    );
  };
};

<name username={this.state.username} />