DEV Community

Gilson Gangadhar
Gilson Gangadhar

Posted on

React Hooks

INTRODUCTION :

As someone who started learning javascript, React and other framesWorks to be a Front-end developer, I have learnt that function components are only used for displaying react elements on the web page. And it's in the class components where we write logic, computation or which adds functionality to the your webpage.

Class component is where we have a local state object, which holds value required by the component and those values are updated using setState() which updates and re-render the component. And it also have lifecycle methods which executes codes within them at different cycles of the class component.

For a beginner, it was bit combursome to see how large & complicated class components became overtime , once it had more state object values, its setState() methods, life cycle methods etc. which became a real problem to comprehend and complicated(i know because most of my initial React apps were made using class components)

That is until recently, i came across React Hooks, which made my life easy just like for millions of Developers WorldWide.

React Hooks :

Hooks was introducted in React Conference 2018, held at Henderson, Nevada, USA, on October 25th & 26th, by Sophie Alpert and Dan Abramov. And it was officially launched in React 16.8.0.

React Hooks let the developer to assign, update & re-render state object values and also use life cycle methods in the function component.

state object & life cycle methods does not exclusively belong to class components anymore.

Rules of Hooks :

i. Call Hooks only at the top level of your react functions. i.e, You shouldn’t call Hooks inside loops, conditions, or nested functions.

ii. Call Hooks from React Functions only. i.e, You shouldn’t call Hooks from regular JavaScript functions.

Now let us see some of the React hooks which are commonly used :

a). State Hooks :

useState() is a Hook using which we add local state to a function component. It returns a pair, the state value you have set & the function which updates your state value.

example of state hook :

const [count, setCount] = useState(0)

here, 'count' is the state value.

setCount is the function which updates the count value. Its similar to setState() of class component, except it updates on the state value of the variable it is assigned to. SetCount() can be called within an eventHandler to update the state value.

And the argument assigned to hook : useState() is the initial value of the 'Count' which is 0.

we create new state value using the above example. Using useState(), we can create setState() functions whcih only updates that perticular state value you have assigned. And it is much more simpler to use than class component's state object.

b). Effect Hooks :

useEffect() is the hook, which do similar functions as life cycle method(of class components) in the function components, where a block of codes can be executed at various points of function component rendering.

some of the examples are :

  • syntax of useEffect() to execute at every render of function component :

useEffect(() => {

console.log('at every render')

})

here, the useEffect will be executed at every render of the function component.

  • componentDidMount() : its the life cycle method of class component which is called at the first render ONLY ONCE, at the beginning. Its not called after the first render of the class component.

syntax of useEffect() which does the similar function, as componentDidMount() :

useEffect(() => {

//codes

},[])

the above useEffect() is only called at the first render of the function component. here [] is called 'dependency array', and its left empty in this case.

  • componentDidUpdate(props) : its a lifecycle method of class component, which is called every time props value changes.

syntax of useEffect() which does the similar function, as componentDidUpdate(props) :

useEffect(() => {

console.log(the name changed : ${name})

},[name] )

here, the 'name' in the dependancy array is the props. And useEffect() is called everytime value of the 'name' changes. Here dependency array can have many values, seperated by comma.

  • componentWillUnmount() : its a life cycle method, which is called, once the component unmounts to re-render(its not called at the first render of the component).

syntax of useEffect() which does the similar function, as componentWillUnmount() :

useEffect(() => {

return () => {
console.log('component unmounted')
}

}, [])

here the useEffect() returns a function, which is called a "clean-up" function, which is executed once the component unmounts to re-render. Only the codes within the clean-up function is executed before the component unmounts to re-render.

c). useRef hook :

useRef allows us to get access to any DOM element which is same as working with ref in react.

Syntax of useRef()

const refContainer = useRef(initialValue)

example :

const App = () => {
const [username, setUsername] = useState("");
const usernameRef = useRef();

const handleOnSubmit = event => {
event.preventDefault();
setUsername(usernameRef.current.value);
usernameRef.current.value = "";
};

return (
type="text"
name="username"
placeholder="Enter your name"
autoComplete="off"
ref={usernameRef}
)

As you can see we have created the reference using :

const usernameRef = useRef();

and assigned it to the input field. So now we can access the input field by using usernameRef.current property anytime we want to get access to the input field.

useRef is not exactly same as React ref because useRef returns a mutable ref object whose .current property is initialized to the passed argument.

Top comments (0)