DEV Community

Cover image for React Hook (useState,useEffect,useContext)
Hossen Mahmud
Hossen Mahmud

Posted on

React Hook (useState,useEffect,useContext)

Hooks are the new feature introduced in the React 16.8 version. It allows us to use state and other React features without writing a class.
When to use a Hooks:
If we write a function component and then we want to add some state to it, previously we do this by converting it to a class. But, now we can do it by using a Hook inside the existing function component.

Rules to use Hooks:

  • Only call Hooks from React functions,
  • Only Call Hooks at the Top Level.
  • Hooks can call other Hooks
  • Don't call Hooks inside loops, conditions, or nested functions

Basic Hooks:

  • useState
  • useEffect
  • useContext

Additional Hooks:

  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue In this blog, we discuss react basic hooks

useState

The useState hook allows us to create state variables in a React function component.
The state allows us to access and update certain values in our components over time
When we create a state variable, we must provide it with a default value (which can be any data type).
Example:
Initialize state at the top of the function component.

Image description
Notice that again, we are destructuring the returned values from useState.The first value, color, is our current state. The second value, setColor, is the function that is used to update our state.

Read State
We can now include our state anywhere in our component.
Example:

Image description

Update State
To update our state, we use our state updater function.
Example:
Use a button to update the state:

Image description

useEffect

The useEffect Hook allows us to perform side effects in our components. Some examples of side effects are: fetching data, directly updating the DOM, and timers. useEffect accepts two arguments. The second argument is optional. useEffect(, ).

Image description

useContext

useContext Helps Us Avoid Prop Drilling. Context is helpful for passing props down multiple levels of child components from a parent component and sharing state across our app component tree.

Create Context
To create context, you must Import createContext and initialize it

Image description
Next, we'll use the Context Provider to wrap the tree of components that need the state Context.

Context Provider
Wrap child components in the Context Provider and supply the state value.

Image description

Now, all components in this tree will have access to the user Context. Use the useContext Hook.

Image description

Top comments (0)