Show Menu
Cheatography

React 16.8 Includes Hooks this was the first version so far in the react history when hooks were first introduced .

useState

State as Object:
The state is an object that holds inform­ation about a certain component.
Two Factor:
State change is one of the two things that make a React component re-ren­der(the other is a change in props)
Behavior
The state stores inform­ation about the component and controls its behavior.
Updater Function
The setState() function is asynch­ronous .
Time Taken by Re-render
The time it takes for a component to render after a call to setState() depends upon the various factors, including the size and complexity of the component, the speed of the Computer or device and the amount of data being processed .
Optimi­zation
It reduces unnece­ssary re-renders and updates only the components that have changed.
 

useEffect

Side Effects
Actions which are Unpred­ictable because they are performed with the outside world.
Meaning
Side Effects basically means something that happens after Some other specific thing happens.
Common Side Effects
1. Making a request to an API for data on back end server.
2.Interact with browser API e.g. use document or windows directly.
3.Using unpred­ictable timing functions like setTim­eOut() or setInt­erv­al().
How
If we need to perform side effects it should be after the component renders.
useEffect
useEffect has one functi­on(­cal­lback) and an array(­dep­endency array)
Callback
Call back function will be called after the component renders. And this is the function which is used to perform our side effects .
Dependency Array
The depend­encies array should include all of the values that our side Effect relies upon.
1. The array will cause the useState() to execute again if one of its variables changes
2.If provided incorr­ectly the array with the local state. this may cause an infinite loop.
CleanUp Function
When component unmounts this functions cleans up any changes made by effect.
 

useEffect and useState

import React, { useState, useEffect } from 'react';

function Example() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(json => setData(json))
      .catch(error => console.error(error));
  }, []);

  return (
    <div>
      {data.map(post => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.body}</p>
        </div>
      ))}
    </div>
  );
}
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          React & Material UI Project startup Cheat Sheet