React 7

Advanced React:

Hooks, HOCs, Render Props

What are Hooks?

Hooks are from a recent release in React, and allow new features for functional components, including the ability to store state values.

 

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, and enables us to change those values in a way similar to this.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

Higher Order Components

In the simplest terms, a higher order component (HOC) is a component that takes another 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.

React 7

By matias_perez

React 7

Advanced React: Hooks, HOCs, and Render Props

  • 252