Hooks are a new addition in React 16.8. If we write a functional component, and then we want to add some state to it, previously we did this by converting it to a class. But, now we can do it by using a Hook inside the existing functional component.
Some of the hooks that react provides us are
Methods like “componentDidMount()”, “shouldComponentUpdate()”, “componentDidUpdate()”, and “componentWillUnmount()” use used to handle Component lifecycle events. Props are passed to the component through its
constructor() function and the component is rendered in a
The useState hook allows us to create state variables for our component. State variables are used to store dynamic data in our component which can change as a user interacts with it.
useState takes in an initial value as an argument and returns an array containing the state variable and a function to mutate it. It is common practice to de-structure this array and set its contents to be const. This is because the state variable should never be reassigned directly and should only be modified via the setter function. The setter function accepts either a new value or a function which takes the current value as an argument and returns the new value.
The useEffect hook allows us to respond to changes in the component lifecycle. The component lifecycle refers to a set of events that occur from the time a component is mounted to the DOM until it is removed. useEffect is most commonly used to execute code when the component is initially rendered, when it is updated, and when it is unmounted.
useEffect accepts a function and a dependency array as arguments. The function will be executed when a variable in the dependency array changes. If no dependency array is provided, the function will run every time the component is re-rendered. If the dependency array is empty, the function will only be run when the component first mounts to the DOM. A common use case for an empty dependency array would be when fetching data from an API.
Benefits of Hooks
It revolutionizes the way you write components
You can write clearer code.
They are simpler to work with and test. Code would be much easier to read.
It indicates how to make code more reusable and composable.