Skip to content

Commit

Permalink
Add: Add a react hook for storing instance variables
Browse files Browse the repository at this point in the history
An instance variable stores the value directly and doesn't cause
re-renders if it is changed. Variables returned from this hooks are
comparable to instance variables for class components.
  • Loading branch information
bjoernricks committed Jun 6, 2024
1 parent 1a67195 commit 254d64c
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/web/hooks/useInstanceVariable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/* SPDX-FileCopyrightText: 2024 Greenbone AG
*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

import {useRef} from 'react';

/**
* A hook to store an instance variable for a function component.
*
* This variable is persistent during render phases and changes to the variable
* don't cause re-renders like useState does. It is comparable to storing a
* variable to this in a class component.
*
* https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables
*
* @param {*} initialValue Initial value of the variable. Can be any kind of
* object. Most of the time it should be initialized
* with an empty object.
*/
const useInstanceVariable = initialValue => {
const ref = useRef(initialValue);
return ref.current;
};

export default useInstanceVariable;

0 comments on commit 254d64c

Please sign in to comment.