react hooks

Posted by missnadia on July 22, 2019

what are they and how do we use them?

  • added via React 16.8
  • allow use of state and other React features without writing a class
  • allow splitting larger component into smaller functions based on related pieces

introduced to solve following issues in React:

  • unable to attach reusable behavior to a component without having to restructure
  • lack of organizing stateful logic – allows room for error and inconsistencies
  • unable to break down complex components to testable smaller components

new function useState:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me

example from React documentation