Advanced React

Hooks, High Order Components, Render Props

What are Hooks?

Hooks are from a recent release in React, and allow, among other things, the ability to store state values in functional components. To go along with this, lifecycle method functionality is also available through hooks. Today we will cover two main hooks:

useState - for storing state values in functional components

useEffect - for lifecycle method functionality within functional components

useState

The useState hook allows for storing state values within functional components, as well as a function for changing those values (similar to setState)

import React, {useState} from 'react';

const Hooks = () => {
    const [count, setCount] = useState(0);
    
    return (
    	<div>{count}</div>
    )
};    

import useState

name state value

function to change state value

initial value of state item

useState

To change state values, simply use the function you set in the state items declaration:

const countUp = () => {
  setCount(count + 1)
}

useEffect

useEffect can be seen as a combination of lifecycle methods, particularly the componentDidMount and componentDidUpdate methods.

import React, {useEffect} from 'react';

const Hooks = (props) => {
  useEffect(() => {
    console.log('useEffect Fired')
  }, [])

  return (
  	<div>Hooks Component</div>
  )
}

callback function

dependency array

High Order Components

In the simplest terms, a high order component is a function that takes a component as an argument and returns a new component. This is commonly done to reuse common logic through several components.

Render Props

Render props refer to a technique for sharing code between components by passing a 'render' prop that is a function that returns a React element. The receiving component then invokes this function instead of implementing its own render logic.

Advanced React

By Matthew Bodily

Advanced React

  • 272