Hooks, introduced in React v16.8, are a welcome addition allowing the use of state in functional components. Prior to this React update, only class components could hold state. The React docs state that it is not necessary to change all of your existing class components into functional components incorporating hooks. Rather, it is recommended, that moving forward, one begin to use Hooks in functional components and phase out class components.
Hooks cannot be used in class components.
Hooks do not remove any previous functionality, and as of now, there are no plans to replace anything with hooks.
useState Hook
The useState hook allows us to declare a state and update it in a functional component. To get started with the useState hook, import it from React.
import React, {useState} from 'react'
Then, use useState to declare state within a functional component.
const [statefulValue, functionToUpdateState] = useState(initialState)
The useState hook returns two things, a stateful value and a function to update that state. useState() can take in an argument of the initial state.
The functionToUpdateState takes in an argument that becomes the new state. A re-render will occur once this function is invoked.
A functional component with the useState Hook may look like:
const exampleFuncComp = () => {
const [state, setState] = useState(initialState)
setState(newStateValue)
//This will change the state to the value of the argument passed in.
}
Conclusion
There are many Hooks introduced in React 16.8. To learn more about them, read the React docs and start implementing them in your functional components.
Top comments (0)