Lesson 5. Debugging hooks 1. Using the plain old console.log
Although console.log can be unpopular among the developers, no one will deny
that it is the fastest way to debug your issues when they occur. Using
console.log is very useful to list some events when they happen, especially
when they happen quickly—perfect for debugging an effect that isn’t triggered or
a rendering that doesn’t occur.
Result
In this example, we want to present an input to enter a number and display it multiplied by two. There is a bug here: the doubled value is still 0.
Putting some console.log in the component function body or the useEffect can
help us investigate:
// ...console.log('Rendering, value =', value, '| double =', double)useEffect(() => {console.log('In useEffect')setDouble(value * 2)}, [double])// ...
The logs when the component is initially rendered don’t give us many clues:
Rendering, value = 0 | double = 0In useEffect
But here are the logs displayed when we update the value of the input:
Rendering, value = 1 | double = 0Rendering, value = 2 | double = 0
We observe that the value state is updated as expected, but the effect is
never triggered. Why? What we can do then is logging the value of the effect’s
dependencies array. We know that if the array values are not modified, then
React won’t trigger the effect.
useEffect(() => {console.log('In useEffect')setDouble(value * 2)}, [double])console.log('Dependencies array:', [double])
Here are the logs when the value is updated:
Rendering, value = 1 | double = 0Dependencies array: [0]Rendering, value = 2 | double = 0Dependencies array: [0]
The dependencies array still contains 0, the initial value. Maybe you already
guessed the problem: we have double in the dependencies array instead of
value.
Here is the component’s code with all the logs we used:
Result
This example may seem trivial, but it demonstrates how using console.log can
be a first step that will help you most of the time to understand why a state is
not updated or an effect not triggered correctly.
But sometimes, you don’t need to see all the verbose logs for the state changes and prefer a way to know the value of current states without modifying the code. Fortunately, React Devtools will help us here.