React.js useEffect and dependency array
A tutorial code, invoke a state change function, to force a render ( adding a comma using array destructuring).
import React, { useEffect, useState } from "react";
const useAnyKeyToRender = () => {
const [ , forceRender ] = useState();
useEffect( () => {
window.addEventListener( "keydown", forceRender );
return () => window.removeEventListener( "keydown", forceRender );
}, [] );
};
export default function App() {
useAnyKeyToRender();
useEffect( () => {
console.log( "fresh render" );
} );
return <h1>Open the console</h1>;
}
In this hook we don’t care about the state value. We only want the state function: forceRender.
I understand how arrays destructuring works
const [fruit, setFruit] = useState('banana');
is equivalent to
var fruitStateVariable = useState('banana'); // Returns a pair
var fruit = fruitStateVariable[0]; // First item in a pair
var setFruit = fruitStateVariable[1]; // Second item in a pair
I don't understand how this code works
const [ , forceRender ] = useState();
Why the first array element is blank (ignored), and why forceRender is the second element.
Why setForceRender is not used ?
How is invoked forceRender ?
I understood the goal of this hook, but no the dependency array trick.
If i do: console.log(forceRender), appears:
ƒ bound dispatchAction() {}
<constructor>: "Function"
name: "Function"
I don't understand how this hook works, and how forceRender function mechanism. It seems simples but i'm confused.