useState is not always the correct answer❌

In React, we have two ways to manage the component’s state — useState and useReducer. The second is less popular because it is meant for more complex objects in the state and honestly looks too tricky at first glance for new programmers, but it is not….


This content originally appeared on DEV Community and was authored by Srijan Karki

In React, we have two ways to manage the component’s state — useState and useReducer. The second is less popular because it is meant for more complex objects in the state and honestly looks too tricky at first glance for new programmers, but it is not.

However, useState looks very simple and understandable, so new programmers often use it more than is required.

useState

Depending on user interactions, it is intended to manage the state for redrawing components. If you want to remember something without rendering it, you probably shouldn’t put it in the state. useRef would be the best option.

You don‘t need useState if:

You want to remember some values during re-renders without showing them to the user. You already have data in the state, or you receive it through props but need to transform it; you don’t need to keep that new value in the new useState object, create a new variable and operate with that without triggering useless re-renders.

You need to keep the value in a state if:

You want to redraw the component when the value changes; the most popular examples are showing/hiding panels, spinners, error messages, and modifying arrays.

Simplify your code from this:
import React, { useState, useEffect } from 'react';

const MyComponent = (props) => {
  const [name, setName] = useState('name');
  const { description, index } = props;
  const [fullName, setFullName] = useState('');

  useEffect(() => {
    setFullName(`${name} - ${description}`);
  }, [name, description]);

  return (
    <div>
      <h1>{fullName}</h1>
      <input 
        type="text" 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
        placeholder="Enter name" 
      />
      <p>{description}</p>
    </div>
  );
};

export default MyComponent;

This code snippet defines a React component that initializes name and fullName states, and uses the useEffect hook to update fullName whenever name or description changes. It also includes an input field to update the name state and displays the fullName and description.

This approach gives you useless re-renders and unnecessary usage of
useEffect.When the name or description changes and React re-renders the component,React will check if there is functionality that depends on these values. useEffect will be triggered when the name or description changes,creating a new re-render.

To this
import React, { useState } from 'react';

const MyComponent = (props) => {
  const [name, setName] = useState('');
  const { description, index } = props;
  const nameWithDescription = `${name} - ${description}`;

  return (
    <div>
      <h1>{nameWithDescription}</h1>
      <input 
        type="text" 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
        placeholder="Enter name" 
      />
      <p>{description}</p>
    </div>
  );
};

export default MyComponent;

In this code snippet, nameWithDescription is calculated directly from name and description without the need for useEffect. The name state is initialized with an empty string. The nameWithDescription is updated automatically whenever name or description changes due to React's re-rendering mechanism.

we can use React default behaviour and get the correct value when the name or descriptions are changed without triggering one more re-render.


This content originally appeared on DEV Community and was authored by Srijan Karki


Print Share Comment Cite Upload Translate Updates
APA

Srijan Karki | Sciencx (2024-07-19T03:41:29+00:00) useState is not always the correct answer❌. Retrieved from https://www.scien.cx/2024/07/19/usestate-is-not-always-the-correct-answer%e2%9d%8c/

MLA
" » useState is not always the correct answer❌." Srijan Karki | Sciencx - Friday July 19, 2024, https://www.scien.cx/2024/07/19/usestate-is-not-always-the-correct-answer%e2%9d%8c/
HARVARD
Srijan Karki | Sciencx Friday July 19, 2024 » useState is not always the correct answer❌., viewed ,<https://www.scien.cx/2024/07/19/usestate-is-not-always-the-correct-answer%e2%9d%8c/>
VANCOUVER
Srijan Karki | Sciencx - » useState is not always the correct answer❌. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/19/usestate-is-not-always-the-correct-answer%e2%9d%8c/
CHICAGO
" » useState is not always the correct answer❌." Srijan Karki | Sciencx - Accessed . https://www.scien.cx/2024/07/19/usestate-is-not-always-the-correct-answer%e2%9d%8c/
IEEE
" » useState is not always the correct answer❌." Srijan Karki | Sciencx [Online]. Available: https://www.scien.cx/2024/07/19/usestate-is-not-always-the-correct-answer%e2%9d%8c/. [Accessed: ]
rf:citation
» useState is not always the correct answer❌ | Srijan Karki | Sciencx | https://www.scien.cx/2024/07/19/usestate-is-not-always-the-correct-answer%e2%9d%8c/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.