React Hooks 101: useState and useEffect
React components are simply functions. Some are created with classes, better known as stateful and/or class components, and the others are created with functions only, also known as stateless and/or functional components.
In addition to having different syntaxes, stateful components have some more functionality, such as state, lifecicles, constructor, this and etc., while stateless components have always been more used to create 'dumbs components', just for display, without much logic involved.
To get in-Depth knowledge on Reactjs you can enroll for a live demo on Reactjs Online Training
But that has been changing since the arrival of the React Hooks, which is a proposal to facilitate and make development with React more flexible, bridging the gap between stateful and stateless components.
What is React Hooks?
In short: React Hooks are some methods that give more power to your stateless components, like own and independent states, some lifecicles, subscription, logic sharing, reducers and etc. This article will explain two functions presents in React Hooks:
- useState;
- useEffect;
useState
The most basic function of React Hooks is useState. With it, you can add states in a functional stateless component. The useState method takes a parameter, which is the State's initial value, and returns two properties in an array, the first is the State itself and the second is the method used to update it.
Take your career to new heights of success with Reactjs Training
Here some example of how you use state without React Hooks:
With React Hooks:
Always remember to import the function you wanna use your file:
useEffect
The useEffects method is always called when the component is assembled and updated. With it you can replace the componentDidMount, componentDidUpdate and componentWillUnmount lifecicles.
It executes the function inside it and has an optional second parameter, which is an array of properties to be observed within the scope of the stateless component. Whenever any of them are updated, the function is executed again.
Get More info on Reactjs Certfication Course
Here's an example using componentDidMount:
Applying useEffect:
Importing useEffect in the top of your file:
That was a very simple explanation about two functions presents in Reach Hooks.