Giter VIP home page Giter VIP logo

use-force-update's Introduction

useForceUpdate

version minzipped size downloads build

useForceUpdate is a React Hook that forces your function component to re-render.

useForceUpdate does not serve a purpose in and of itself. It is a tiny package that aims to be integrated into larger hooks, making obsolete any class functionality that is still reliant on this.forceUpdate().

Install

  • npm install use-force-update or
  • yarn add use-force-update

Use

In its simplest form, useForceUpdate re-renders a component.

import useForceUpdate from 'use-force-update';

let renderCount = 0;

export default function MyButton() {
  const forceUpdate = useForceUpdate();

  renderCount++;
  return (
    <>
      <p>I have rendered {renderCount} times.</p>
      <button onClick={forceUpdate}>
        Re-render
      </button>
    </>
  );
};

In its ideal form, useForceUpdate integrates with event emitters, such as state managers.

import { useEffect } from 'react';
import useForceUpdate from 'use-force-update';
import store from './store';

export default function MyButton() {
  const forceUpdate = useForceUpdate();

  const username = store.get('username');

  useEffect(() => {
    // When the username changes, re-render this component.
    const selector = state => state.username;
    const unsubscribe = store.subscribe(selector, forceUpdate);

    // When we unmount, stop re-rendering this component.
    return () => {
      unsubscribe();
    };
  }, [forceUpdate]);

  if (username === null) {
    return <p>You are not logged in.</p>;
  }

  return <p>Hello, {username}!</p>;
};

use-force-update's People

Contributors

quisido avatar dependabot-preview[bot] avatar dependabot[bot] avatar forbeslindesay avatar leonardodino avatar

Stargazers

 avatar Jack Pallot avatar Ari Bermeki avatar Tuan Duc Tran avatar Josh Thomas avatar aaa avatar Landon Johnson avatar Angel avatar Anton Savitskiy avatar Aref Hasan avatar ty888 avatar Thitare Nimanong avatar Leon Si avatar  avatar João Chaves avatar Devansh Agarwal avatar Mattia avatar YunHan avatar Spark Cheng avatar  avatar Vinh Truong avatar 清扬陌客 avatar Carlos Sala Samper avatar lalacute avatar luanfujian avatar 도다 avatar Yinka Adedire avatar  avatar Saadh avatar Alexandr Shaporov avatar DongHee Kang avatar  avatar Sergey avatar Simon Ludwig avatar Brad Ackerman avatar  avatar aric avatar Aman Mittal avatar 404 avatar Michael Demarais avatar Roy Lin avatar Tim Seriakov avatar David Fernando avatar Gyubong Lee avatar Ibrahim Azhar Armar avatar S. Tarık Çetin avatar Tom avatar Felipe Cantieri Testoni avatar Scott Burwell, PhD avatar Alex Sandiiarov avatar  avatar Vladimir avatar Jude avatar Nolansym avatar Changsheng Zhu avatar Jeff Schenk avatar PsAiL avatar Alexei Accio avatar ShinHak Kwon avatar Erko Bridee avatar Stanimir avatar Serge Borbit avatar Maurício Rodrigues avatar Alireza TK avatar Bora avatar erri120 avatar Burak avatar Nick K. avatar kevin avatar Roberto Ribeiro avatar 佐七 avatar John W. Nolette avatar lin avatar Acorn1010 avatar Kaio avatar Raja Jaganathan avatar Shun Kakinoki avatar Thang Nguyen avatar Paul Alekseev avatar Pedro Menezes avatar Ilya Medvedev avatar Matias Alibertti avatar Asher Hwang avatar Breno Sena avatar Stoicescu Cristi avatar Kishan Bagaria avatar weikeduopp avatar koji avatar Emmanouil Katefidis avatar Ken Huang avatar Victor Malov avatar  avatar  avatar R o m u l l o avatar  avatar /ðə/ZHIR avatar Jeason avatar Puck Wang avatar Jeffrey Wear avatar  avatar

Watchers

 avatar James Cloos avatar  avatar  avatar Alexandr Shaporov avatar

use-force-update's Issues

Update component from other components function.

Nice package and it works like expected! I would like to ask if something like this is possible but for now, everything I tried did not work.

import Nav from './nav';

const myFunc= () => {
      forceUpdate(<Nav />); 
  };

The problem I face that the function that runs on the click is in another component then the component that needs force-rerender, Is there any way to achieve this? Thanks

Stopped working?

This hook stopped working, No Component Updates are triggered anymore. Any chance to fix this?

Proposed Improvements

Current Code

export default function useForceUpdate(): () => void {
  const [ , dispatch ] = useState<{}>(Object.create(null));

  // Turn dispatch(required_parameter) into dispatch().
  const memoizedDispatch = useCallback(
    (): void => {
      dispatch(Object.create(null));
    },
    [ dispatch ],
  );
  return memoizedDispatch;
}

Proposed Improvements

JS, but can easily be typed:

import { useRef, useState } from 'react';

// Creates an empty object, but one that doesn't inherent from Object.prototype
const newValue = () => Object.create(null);

export default () => {
  const setState = useState(newValue())[1];

  const forceUpdate = useRef(() => {
    setState(newValue());
  }).current;

  return forceUpdate;
};

Rational:

First, dispatch unclear. Looking at the history, it is a residue from when useReducer was used, but this is no longer the case.

Then, from the docs (see note):

React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.

So there's no need providing it as a useCallback dependency.

Either useCallback or useMemo with empty dependencies ([] - ie, one-off) is identical to useRef().current which somehow communicates the intent better - this value will not change. Also, with useRef, react doesn't call Object.is(old, new) each render.

Also note that in the current code we have memoizedDispatch but because dispatch is stable, there's no real memoization going on - useCallback will always return the same function.


Finally, in my case, initial render could trigger dozens of forceUpdates so a further improvement could be (I'm not actually using it because the trade-off doesn't seem to be worth it, but others may find this useful):

import { useRef, useState, useEffect } from 'react';

// Creates an empty object, but one that doesn't inherent from Object.prototype
const newValue = () => Object.create(null);

export default () => {
  const setState = useState(newValue())[1];

  const updatePending = useRef(false);

  const forceUpdate = useRef(() => {
    if (!updatePending.current) {
      setState(newValue());
      updatePending.current = true;
    }
  }).current;

  useEffect(() => {
    updatePending.current = false;
  });

  return forceUpdate;
};

Less complex implementation

wouldn't this work just as well? none of the max nonsense.

const useForceUpdate = () => {
  const [, setIt] = useState(false);
  return () => setIt(it => !it);
};

Latest update no longer works with reactn

After updating to latest version (1.0.7 to 1.0.10) of use-force-update, my react native app no longer works and yields the follow error:

error: Error: While trying to resolve module `use-force-update` from file `/Users/me/development/bind-react/node_modules/reactn/build/use-global.js`, the package `/Users/me/development/bind-react/node_modules/use-force-update/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/me/development/bind-react/node_modules/use-force-update/dist/cjs/index.cjs`. Indeed, none of these files exist:

  * /Users/me/development/bind-react/node_modules/use-force-update/dist/cjs/index.cjs(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
  * /Users/me/development/bind-react/node_modules/use-force-update/dist/cjs/index.cjs/index(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
    at DependencyGraph.resolveDependency (/Users/me/development/bind-react/node_modules/metro/src/node-haste/DependencyGraph.js:243:17)
    at Object.resolve (/Users/me/development/bind-react/node_modules/metro/src/lib/transformHelpers.js:129:24)
    at resolve (/Users/me/development/bind-react/node_modules/metro/src/DeltaBundler/traverseDependencies.js:396:33)
    at /Users/me/development/bind-react/node_modules/metro/src/DeltaBundler/traverseDependencies.js:412:26
    at Array.reduce (<anonymous>)
    at resolveDependencies (/Users/me/development/bind-react/node_modules/metro/src/DeltaBundler/traverseDependencies.js:411:33)
    at processModule (/Users/me/development/bind-react/node_modules/metro/src/DeltaBundler/traverseDependencies.js:140:31)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async addDependency (/Users/me/development/bind-react/node_modules/metro/src/DeltaBundler/traverseDependencies.js:230:18)
    at async Promise.all (index 13)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.