top of page
Search
  • Writer's pictureKayla Miller

Using useState & useEffect React Hooks

Both useState and useEffect enhance functional components to make them do things that classes can but functional components (without hooks) cannot:

  • useState allows functional components to have state.A key difference between class and functional components is the fact that class components have a state while functional components are stateless. The


hook allows us to add local state to a functional component. This hook holds onto a state between re-renders.


1. Importing useState

First things first. Make sure to import { useState } from “react”

import {useEffect} from "react";

2. Declaring the state variable for the component

To declare the state variable, a pair of values needs to be set equal to the useState method. The pair of values are the current state and a function that updates the current state. useState will always return this pair of values.

function App() {

const [state, setState] = useState([]); }


3. Initializing the state by passing in the initial value in the useState method

The state of the variable is initialized by passing an initial value in the useState method.


  • useEffect allows functional components to have lifecycle methods in one single API. The useEffect hock lets us implement lifecycle methods to tell the component to perform an "effect" after it is rendered. The different types of effects are limitless such as changing the background image or document title, adding animations or music, data fetching, and subscriptions. The useEffect hook allows us to use React's lifecycle methods within a stateless component.


1. Importing useEffect Again, always make sure you are importing at the top!

import {useEffect} from "react";

2. useEffect can be called more than once. useEffect can be called two separate times, with different arguments passed inside.


3. The useEffect Hook allows you to perform side effects in your components.


Some examples of side effects are: fetching data, directly updating the DOM, and timers. useEffect accepts two arguments. The second argument is optional.


3 views0 comments

Recent Posts

See All

Job Search

I started my job search earlier this month and it is more challenging to find a good fitting job. I had a couple job offers however a lot...

Comments


Post: Blog2_Post
bottom of page