I haven't touched React recently, but I read News that React Hooks has been officially released, so I read the official manual of React Hooks to see what it is all about.
summary
In React, there are two ways to create a component: by function or by class, but the function method does not allow components to store state.
With React Hooks, you can create a state storage area (state) that is tied to the function component, and the function component can also store state.
This allows function components to be treated equally with class components.
Since the class component is not very clean to write, Facebook seems to want to promote the function component in the future, which can be written more clearly.
Examples & Explanations
- Clicking on A increases the number by 1 from 0.
- Click on B to increase by 10 to 10
import React, { useState } from 'react'; function Example() { const [countA, setCountA] = useState(0); const [countB, setCountB] = useState(10); return ( <div> <p>You clicked {countA} & {countB} times</p> <button onClick={() => setCountA(countA + 1)}> Click me A </button> <button onClick={() => setCountB(countB + 10)}> Click me B </button> </div> ); }
useState(<initial value>)
is the Hook function, which when called allocates an area to hold the state and returns [\, \ ]. - When \
is called, the state of the allocated area is updated and the function component is redrawn. - When the function component is redrawn,
useState(<initial value>)
is called again, but after the second call, it does not allocate the area but returns the current state of the already allocated area and its update function. - Allocation by
useState(<initial value>)
is done in the order in which they are called, souseState(<initial value>)
is at the top level and the calling order is fixed and must not be changed dynamically.
impressions
I usually use React+Redux, but the amount of coding to do little things was just too much.
I was hoping that React Hooks would solve that problem, but since I rarely use component states with Redux, I thought it wouldn't matter much.