Since React hooks came out with React 16.8, I’ve seen many hooks tutorials popping up. They are surely interesting and I recommend them, but they can be sometimes a bit long and scary. In any case, as always I think it is beneficial to explain things with different words.
In a nutshell, React Hooks are used to add state and lifecycle to function components, which, prior to Hooks, could only be “dumb” and print whatever props they were passed from outer components.
In this post I want to show the simplest React Hooks example. It contains both “useState”, used make use of state inside the component, and “useEffect”, used to run code when the component is loaded, or when props or state change.
So, here is my example, which is hopefully pretty self explanatory. (click on the coloured buttons to switch between editor and browser view)
What is happening?
On lines 6 and 7 we set two state variables we want to use (showText and text), along with two actions used to update them (setShowText and setText). We also set starting values for those two variables.
To be more precise, when we set:
const [text, setText] = useState('')
We are setting the variable “text” to a starting value of an empty string, and also setting up a “setText” function which we will be able to use to update the “text” variable later in the code.
On line 9, we have a handleClick function. When it runs, it sets the showText variable to the opposite of what it was, effectively toggling between a true and a false state.
On line 12, we have the useEffect function. As the React docs say, “you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined”. This means this useEffect function will run when the component mounts, and everytime we update it by changing its props.
Then from line 18 to 21 we render the component.
So that’s it, there are the basics of React Hooks. If you would like to discuss it, you can do so on Linkedin:
I have written (hopefully) the simplest practical React Hooks tutorial
— Alessandro Muraro – February 21, 2019