When we want to display the current count in a class, we read this.state.count:

<p>You clicked {this.state.count} times</p>
In a function, we can use count directly:

<p>You clicked {count} times</p>
In a function component, we have no this, so we can’t assign or read this.state. Instead, we call the useState Hook directly inside our component:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);

This should help you understand how to initialize, set and use state using the useState hook. Please read comments too.


import React, { useState } from 'react';


// pinError & pin are deconstructed state passed down and are used as the initial values of your pinError & pin state
const PinInput = ({pinError, pin}) => {

    const [newPinError, setNewPinError] = useState(pinError); // initialize state
    const [newPin, setNewPin] = useState(pin);

    const handleValidatePinDigit = (e) => {
        const isValidPin = isValidPinDigit(e.target.value);
        const updatedPin = isValidPin ? e.target.value : '';

        setNewPinError(!isValidPin); // set state 
        setNewPin(updatedPin);       
    };

    // this printPin function shows how to use state 
    const printPin = () => {
        if (newPinError) { 
            console.log("[pinError] Your invalid pin is: " + newPin);
        } else {
            console.log("Your valid pin is: " + newPin);
        }
    }
};

useRef to read future value


  const [activePoint, _setActivePoint] = React.useState(null);

  // define a ref
  const activePointRef = React.useRef(activePoint);

  // in place of original `setActivePoint`
  const setActivePoint = x => {
    activePointRef.current = x; // keep updated
    _setActivePoint(x);
  };

  const handleResize = () => {
    // now when reading `activePointRef.current` you'll
    // have access to the current state
    console.log(activePointRef.current);
  };

  const resizerMouseDown = /* still the same */;

  return /* return is still the same */

You can map items into new array and when the item key matches the key parameter update the text property.


let updateToDo = (value, key) => {
  const allItem = items.map(item => {
    const newItem = {...item};
    if (item.key === key) {
      newItem.text = value;
    }
    return newItem;
  });
  console.log(...allItem);
  addItem(allItem);
};

The hook you are creating manages the state of nations and returns it. Instead of useState you are using useLocalStorage which, as far as I could read from the source, uses as initial state a localStorage value or the given value (null in your case) if there is no local one.


export const useNations = ():
    | NationResource[]
    | null => {
    const [storedNations, setStoredNations] = useLocalStorage<
        NationResource[] | null
    >("nations", null);

    useEffect(() => {
        // If storedNations has a value don't continue.
        if (storedNations) {
            return;
        }

        const fetch = async () => {
            // Check the types here, Im not sure what NationsGetResponse has.
            const nationsResponse = await Axios.get<NationsGetResponse>(
                "/v1/nations/"
            );

            setStoredNations(nationsResponse.data.nations);
        };

        fetch();
    }, []);

    return storedNations;
};

To perform effects in response to state changes, use the useEffect hook. You can read more about it here. In your case, you'd want to do something like


import React, { useEffect } from 'react';
import { useFieldArray } from 'react-hook-form';

const MyComponent = () => {
  const { fields, append } = useFieldArray(...);

  useEffect(() => {
    // this callback will run once on initial render and
    // then again whenever `fields` is updated
    console.log('fields 2', fields);
  }, [fields]);

  return (
    <div>
      <button onClick={() => {
          console.log('fields 1', fields);
          append({ item: { id: 1, name: 'test' } });
        }}>
        Click me
      </button>
    </div>
  );
};

the dependency value in the useEffect hook is the reason for the update loop. Once you set the state, it would trigger an update which also triggers fetching and setting the state again. if getLimitsFromGen(validGeneration) is not an async function, you can set the return value of getUrl as your dependency. Read more about how to use useEffect here. Also try renaming your fetch() function to something more specific, as already mention fetch is an inbuilt js function


 const [state, set_state] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const res = await axios.get(`${genUrl()}`);
      set_state(res.data);
    }
    fetchData();
  },[genUrl()]);
  const fetchedData = state.results;

A solution is to either use mutable state, or access state exclusively from state updater function. In the code above, state.isMouseDown refers to original state. In case it's needed to avoid state updates, state updater can return original state:


  const mouseMove = () => {
    setState(state => {
      if (!state.isMouseDown)
        return state; // skip state update
      else
        return {
          ...state,
          isMouseMoving: true
        };
    });
  };

Recommend

React Using the State Hook Declaring a State Variable

React Using the State Hook What’s a Hook?

React Using the State Hook Hooks and Function Components

React Using the State Hook Equivalent Class Example

React Using the State Hook

React Handling Events Passing Arguments to Event Handlers

React Handling Events

React Hello World

React Rules of Hooks Explanation

React Rules of Hooks ESLint Plugin

React Introducing Hooks

ReactDOMServer Reference renderToStaticNodeStream()

ReactDOMServer Reference renderToNodeStream()

ReactDOMServer Reference renderToStaticMarkup()

ReactDOMServer Reference renderToString()

ReactDOMServer

React Testing Recipes Multiple Renderers

React Testing Recipes Snapshot Testing

React Testing Recipes Timers

React Testing Recipes Events

React Testing Recipes Mocking Modules

React Testing Recipes Data Fetching

React Testing Recipes Rendering

React Testing Recipes act()

React Testing Recipes Setup/Teardown

React Rendering Elements Updating the Rendered Element

React Rendering Elements Rendering an Element into the DOM

React Rendering Elements

React Component State What is the difference between passing an object or a function in setState?

React Component State Why is setState giving me the wrong value?

React Refs and the DOM Callback Refs

React Refs and the DOM Accessing Refs Refs and Function Components

React Refs and the DOM Accessing Refs Adding a Ref to a Class Component

React Refs and the DOM Accessing Refs Adding a Ref to a DOM Element

React Refs and the DOM Accessing Refs

React Refs and the DOM Creating Refs

File Structure Is there a recommended way to structure React projects? Grouping by file type

File Structure Is there a recommended way to structure React projects? Grouping by features or routes

Glossary of React Terms Components props.children

Glossary of React Terms Components props

Glossary of React Terms Components

Glossary of React Terms Elements

Glossary of React Terms JSX

React Code-Splitting Named Exports

React Code-Splitting Route-based code splitting

Code-Splitting React.lazy Error boundaries

Code-Splitting React.lazy

React Code-Splitting import()

React Code-Splitting Bundling Example

React Test Utilities Other Utilities Simulate

React Test Utilities Reference renderIntoDocument()

React Test Utilities Reference findRenderedComponentWithType()

React Test Utilities Reference scryRenderedComponentsWithType()

React Test Utilities Reference findRenderedDOMComponentWithTag()

React Test Utilities Reference scryRenderedDOMComponentsWithTag()

React Test Utilities Reference findRenderedDOMComponentWithClass()

React Test Utilities Reference scryRenderedDOMComponentsWithClass()

React Test Utilities Reference findAllInRenderedTree()

React Test Utilities Reference isCompositeComponentWithType()

React Test Utilities Reference isCompositeComponent()

React Test Utilities Reference isDOMComponent()

React Test Utilities Reference isElementOfType()

React Test Utilities Reference isElement()

React Test Utilities Reference mockComponent()

React Test Utilities Reference act()

React Test Utilities