avatarsupraja

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2101

Abstract

values which is used in JSX to render. When there is a change in state, react re-renders the part(JSX) that got changed, it means that the component function gets executed again.</p></blockquote><p id="b5b9"><b>Accepts</b> an optional argument, which can be a valid javascript value, to set initial value to state variable.</p><p id="b466"><b>Returns </b>array of two values. The first one is the current value of state variable. The second one is the method to update the state variable</p><div id="af68"><pre><span class="hljs-keyword">const</span> [state, setState] = <span class="hljs-title function_">useState</span>(initialValue);</pre></div><p id="3c75">NOTE: We don’t update state variable directly, but by using setState method, because react uses virtual DOM and it updates virtual DOM, it doesn’t update actual DOM. Then differentiation algorithm is applied between these two DOMs and only the changed portion is re-rendered by react.</p><p id="74c5"><b>Example with code:</b></p><div id="480b"><pre><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span>,{ useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">StateHookExample</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">const</span> white = <span class="hljs-string">'#ffffff'</span>; <span class="hljs-keyword">const</span> black = <span class="hljs-string">'#000000'</span>; <span class="hljs-keyword">const</span> [isWhite, setIsWhite] = <span class="hljs-title function_">useState</span>(<span class="hljs-literal">true</span>); <span class="hljs-keyword">const</span> [hello, setHello] = <span class="hljs-title function_">useState</span>(<span class="hljs-string">''</span>); <span class="hljs-keyword">return</span> ( <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{backgroundColor:</span> <span class="hljs-attr">isWhite<

Options

/span> ? <span class="hljs-attr">white</span> <span class="hljs-attr">:</span> <span class="hljs-attr">black</span>}}></span> <span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> { setIsWhite( (prevState) => !prevState ); }}>Toggle background<span class="hljs-tag"></<span class="hljs-name">button</span>></span> <span class="hljs-tag"><<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{color:</span> !<span class="hljs-attr">isWhite</span> ? <span class="hljs-attr">white</span> <span class="hljs-attr">:</span> <span class="hljs-attr">black</span>}}></span>{hello}<span class="hljs-tag"></<span class="hljs-name">p</span>></span> <span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> { setHello('Hello!'); }}>Say hello<span class="hljs-tag"></<span class="hljs-name">button</span>></span> <span class="hljs-tag"></<span class="hljs-name">div</span>></span></span> ); } <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">StateHookExample</span>;</pre></div><p id="6477">This example shows two state variables, isWhite and hello.

React hooks with examples

React hooks are the javaScript functions that manage the state’s behaviour and side effects by isolating them from a component.

Using react hooks, we hook into react lifecycle. The following are the stages of react lifecycle in simple terms, where hooks come into picture: 1. When component mounts 2. When state changes 3. When props changes 4. When context or store changes 5. When component unmounts

For example, at stage 1, 2 -> useState, useEffect are used at stage 4 -> useContext, useReducer are used

React provides a bunch of standard in-built hooks:

  • useState: To manage states. Returns a stateful value and an updater function to update it.
  • useEffect: To manage side-effects like API calls, subscriptions, timers, mutations, and more.
  • useContext: To return the current value for a context.
  • useReducer: A useState alternative to help with complex state management.
  • useCallback: It returns a memorized version of a callback to help a child component not re-render unnecessarily.
  • useMemo: It returns a memoized value that helps in performance optimizations.
  • useRef: It returns a ref object with a .current property. The ref object is mutable. It is mainly used to access a child component imperatively.
  • useLayoutEffect: It fires at the end of all DOM mutations. It's best to use useEffect as much as possible over this one as the useLayoutEffect fires synchronously.

1. useState:

Used to declare and track the component’s state variable’s value. State is the data of component we deal with, and that data holds certain values which is used in JSX to render. When there is a change in state, react re-renders the part(JSX) that got changed, it means that the component function gets executed again.

Accepts an optional argument, which can be a valid javascript value, to set initial value to state variable.

Returns array of two values. The first one is the current value of state variable. The second one is the method to update the state variable

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

NOTE: We don’t update state variable directly, but by using setState method, because react uses virtual DOM and it updates virtual DOM, it doesn’t update actual DOM. Then differentiation algorithm is applied between these two DOMs and only the changed portion is re-rendered by react.

Example with code:

import React,{ useState } from 'react';

function StateHookExample() {
    const white = '#ffffff';
    const black = '#000000';
    const [isWhite, setIsWhite] = useState(true);
    const [hello, setHello] = useState('');
    return (
        <div style={{backgroundColor: isWhite ? white : black}}>
            <button onClick={() => {
                setIsWhite( (prevState) => !prevState );
            }}>Toggle background</button>
            <p style={{color: !isWhite ? white : black}}>{hello}</p>
            <button onClick={() => {
                setHello('Hello!');
            }}>Say hello</button>
        </div>
    );
}
export default StateHookExample;

This example shows two state variables, isWhite and hello. - On clicking on ‘Toggle background’ button, we update(toggle) state variable(isWhite), based on previous state value. - On clicking on ‘Say hello’ button, we just update state variable without considering previous state value.

2. useEffect:

References: https://github.com/Wavez/react-hooks-lifecycle?tab=readme-ov-file https://www.freecodecamp.org/news/react-hooks-fundamentals/

Reactjs
Hooks
JavaScript
React Lifecycle
Recommended from ReadMedium