Research optimising, and usage of React hooks #250

Closed
opened 2026-04-13 08:25:24 +00:00 by c24elipe · 13 comments
Collaborator
No description provided.
Collaborator

Commonly used Hooks:

  1. State Hooks: useState, useReducer
  2. Effect Hooks: useEffect, useLayoutEffect
  3. Context Hooks: useContext
  4. Ref Hooks: useRef
  5. Callback Hooks: useCallback, useMemo
  6. Layout Hooks: useDimensions, useWindowSize
  7. Form Hooks: useForm
  8. Animation Hooks: useSprings
  9. Custom Hooks

Medium

Commonly used Hooks: 1. State Hooks: useState, useReducer 2. Effect Hooks: useEffect, useLayoutEffect 3. Context Hooks: useContext 4. Ref Hooks: useRef 5. Callback Hooks: useCallback, useMemo 6. Layout Hooks: useDimensions, useWindowSize 7. Form Hooks: useForm 8. Animation Hooks: useSprings 9. Custom Hooks [Medium](https://medium.com/womenintechnology/what-are-the-different-types-of-hooks-in-react-470fdeb86b9)
Collaborator

Rules of using Hooks:

  1. Only call Hooks at the top level

Reason: The order in which Hooks are called is important. If Hooks are placed inside loops, conditionals, or nested functions, react is not able to keep track of the order. The result of having inconsistency with Hook calls are that the apps behavior can break which will result in bugs and performance issues.

Example:

Breaks the rule:

function MyComponent() {
  if (someCondition) {
    // ❌ Breaking the rule: calling useState inside a conditional
    const [count, setCount] = useState(0);
  }

  return <div>Hello, world!</div>;
}

Correct way:

function MyComponent() {
  // ✅ Always call Hooks at the top level
  const [count, setCount] = useState(0);

  if (someCondition) {
    // You can use the value of count inside the condition
    return <div>{count}</div>;
  }

  return <div>Hello, world!</div>;
}
  1. Only call Hooks from React Functions

Reason: Hooks were made with the purpose of managing state and effects in React components. So if Hooks were used outside of React Functions their behavior would break their intended use. React would not be able to handle it.

Example:

Breaks the rule:

function myHelperFunction() {
  // ❌ Breaking the rule: calling useState inside a regular function
  const [count, setCount] = useState(0);
  return count;
}

function MyComponent() {
  const count = myHelperFunction();
  return <div>{count}</div>;
}

Correct Way:

function MyComponent() {
  // ✅ Calling Hooks only in React function components
  const [count, setCount] = useState(0);

  return <div>{count}</div>;
}

Medium

Rules of using Hooks: 1. Only call Hooks at the top level Reason: The order in which Hooks are called is important. If Hooks are placed inside loops, conditionals, or nested functions, react is not able to keep track of the order. The result of having inconsistency with Hook calls are that the apps behavior can break which will result in bugs and performance issues. Example: **Breaks the rule:** ```html function MyComponent() { if (someCondition) { // ❌ Breaking the rule: calling useState inside a conditional const [count, setCount] = useState(0); } return <div>Hello, world!</div>; } ``` **Correct way:** ```html function MyComponent() { // ✅ Always call Hooks at the top level const [count, setCount] = useState(0); if (someCondition) { // You can use the value of count inside the condition return <div>{count}</div>; } return <div>Hello, world!</div>; } ``` 2. Only call Hooks from React Functions Reason: Hooks were made with the purpose of managing state and effects in React components. So if Hooks were used outside of React Functions their behavior would break their intended use. React would not be able to handle it. Example: **Breaks the rule:** ```html function myHelperFunction() { // ❌ Breaking the rule: calling useState inside a regular function const [count, setCount] = useState(0); return count; } function MyComponent() { const count = myHelperFunction(); return <div>{count}</div>; } ``` **Correct Way:** ```html function MyComponent() { // ✅ Calling Hooks only in React function components const [count, setCount] = useState(0); return <div>{count}</div>; } ``` [Medium](https://medium.com/@finnkumar6/the-rules-of-hooks-in-react-what-you-need-to-know-9a6f2ccbf5cc)
Collaborator

What is a Hook?

A React Hook is a special function in React that lets developers use state and other React features without making a class. It makes code simpler and easier to manage by allowing functionality to be added directly within React components.

Medium

What is a Hook? A React Hook is a special function in React that lets developers use state and other React features without making a class. It makes code simpler and easier to manage by allowing functionality to be added directly within React components. [Medium](https://www.uxpin.com/studio/blog/react-hooks/)
Collaborator

What is a Custom Hook?

Custom Hook is a JavaScript function that starts with "use". It allows a user to define hooks for specific purpose. For example a hook for fetching data. It usually combines one or more built in React Hooks. The custom hook would, for example be named "useFetch". One reason for using Custom Hook is to remove duplication of code.

Medium

What is a Custom Hook? Custom Hook is a JavaScript function that starts with "use". It allows a user to define hooks for specific purpose. For example a hook for fetching data. It usually combines one or more built in React Hooks. The custom hook would, for example be named "useFetch". One reason for using Custom Hook is to remove duplication of code. [Medium](https://deadsimplechat.com/blog/custom-hooks-react/)
Collaborator

How to create a Custom Hook:

  1. Identify duplication of code.
  2. Declare a function and name it something with "use" first, for example "useFetch".
  3. Make the file(e.g. useFetch.js), create the function and then export it.
  4. Import the Custom Hook in main file(Main.js).

Medium

How to create a Custom Hook: 1. Identify duplication of code. 2. Declare a function and name it something with "use" first, for example "useFetch". 3. Make the file(e.g. useFetch.js), create the function and then export it. 4. Import the Custom Hook in main file(Main.js). [Medium](https://deadsimplechat.com/blog/custom-hooks-react/)
Collaborator

Hooks let you use different React features from your components.

useState():
The useState function returns a pair [state-variable, setter]. The setter should always be used to change the state. State variables have two main functions:

  • Saving data between renders. When a re-render occurs, all local variables return to their initial values. useState lets components save and change data between renders. The component remembering data is useful for when changing something that needs the component to be rendered again, like changing what data is displayed.
  • The setter causes a re-render. When data changes, we want to be able to see that. Updating a local variable doesn't change the look of the component. If for example the forecast gets updated, then the card containing that data should also be updated. Using the setter ensures that the new state gets shown on the site.

useContext():
Allows components to retrieve data from parents far up the component tree. You can for example get the current theme from the root element without having to pass it down as a prop to each and every component.. Context is created by using the createContext() function.

useEffect():
Simplified a bit from here. There are two types of logic in a react component:

  • Rendering code, pure functions that run when the component is rendered and return HTML, and
  • Event handlers, code nested inside component. This code is run when users interact with components and handles the user interaction by changing states and whatever.

Unlike rendering code and event handlers which are only executed on rendering and user interaction, useEffect allows a function to be run after react is finished rendering. It's mostly used when 'synchronizing' with external systems (eg. fetching data from API) since it allows the website to be rendered before waiting on responses from external systems.

[Hooks let you use different React features from your components.](https://react.dev/reference/react/hooks) useState(): The useState function returns a pair [state-variable, setter]. The setter should **always** be used to change the state. State variables have two main functions: - **Saving data between renders.** When a re-render occurs, all local variables return to their initial values. useState lets components save and change data between renders. The component remembering data is useful for when changing something that needs the component to be rendered again, like changing what data is displayed. - **The setter causes a re-render.** When data changes, we want to be able to see that. Updating a local variable doesn't change the look of the component. If for example the forecast gets updated, then the card containing that data should also be updated. Using the setter ensures that the new state gets shown on the site. useContext(): Allows components to retrieve data from parents far up the component tree. [You can for example get the current theme from the root element without having to pass it down as a prop to each and every component.](https://react.dev/reference/react/hooks#context-hooks). Context is created by using the [createContext()](https://react.dev/reference/react/createContext#creating-context) function. useEffect(): [Simplified a bit from here.](https://react.dev/learn/synchronizing-with-effects) There are two types of logic in a react component: - **Rendering code**, [pure functions](https://react.dev/learn/keeping-components-pure) that run when the component is rendered and return HTML, and - **Event handlers**, code nested inside component. This code is run when users interact with components and handles the user interaction by changing states and whatever. Unlike rendering code and event handlers which are only executed on rendering and user interaction, useEffect allows a function to be run after react is finished rendering. It's mostly used when '[synchronizing](https://react.dev/learn/synchronizing-with-effects)' with external systems (eg. fetching data from API) since it allows the website to be rendered before waiting on responses from external systems.
Owner

Are we creating this for the coding standard?

That is a very good idea since there are many ways to do the same thing in react, and I prefer that we choose a small subset to make the code more maintainable.

Are we creating this for the coding standard? That is a very good idea since there are many ways to do the same thing in react, and I prefer that we choose a small subset to make the code more maintainable.
Collaborator

Advantages to using Hooks:

  • Simplicity and Readability: Using Hooks will lead to a more concise and easy to read code. This will then make it a better developer experience for those who are new to react.

  • Code Reusability: Using Hooks makes it easy to build reusable logic. For example by moving common tasks into Custom Hooks, we can use that Hook across multiple different components without repeating ourselves.

  • No Need for Classes: Hooks allow us to move away from class components entirely and allows for a purely functional approach. This also aligns with React best practices.

Medium

Advantages to using Hooks: - **Simplicity and Readability**: Using Hooks will lead to a more concise and easy to read code. This will then make it a better developer experience for those who are new to react. - **Code Reusability**: Using Hooks makes it easy to build reusable logic. For example by moving common tasks into Custom Hooks, we can use that Hook across multiple different components without repeating ourselves. - **No Need for Classes**: Hooks allow us to move away from class components entirely and allows for a purely functional approach. This also aligns with React best practices. [Medium](https://www.geeksforgeeks.org/reactjs/advantages-and-disadvantages-of-using-hooks-compared-to-class-components/)
Collaborator

Disadvantages to using Hooks:

  • Compatibility Issues: Hooks were created in React 16.8 and there are some already existing codebases that are using heavily incorporated class components. Switching to Hooks might take a lot of effort, time and money.

  • Backward Compatibility: Hooks are not backward compatible with class components. This means that any migration from using class based code to Hooks will require a significant refactoring.

Disadvantages to using Hooks: - **Compatibility Issues**: Hooks were created in React 16.8 and there are some already existing codebases that are using heavily incorporated class components. Switching to Hooks might take a lot of effort, time and money. - **Backward Compatibility**: Hooks are not backward compatible with class components. This means that any migration from using class based code to Hooks will require a significant refactoring.
Collaborator

@hGustavs wrote in #250 (comment):

Are we creating this for the coding standard?

That is a very good idea since there are many ways to do the same thing in react, and I prefer that we choose a small subset to make the code more maintainable.

Yes

@hGustavs wrote in https://git.webug.se/Andras/BoundlessFlowCampus2K/issues/250#issuecomment-2412: > Are we creating this for the coding standard? > > That is a very good idea since there are many ways to do the same thing in react, and I prefer that we choose a small subset to make the code more maintainable. Yes
Collaborator

I've written a bit about react and how it works on the wiki. It's not quite done yet but some input would be nice. Some of the information is taken from #114

I've written a bit about react and how it works on the [wiki](https://git.webug.se/Andras/BoundlessFlowCampus2K/wiki/React). It's not quite done yet but some input would be nice. Some of the information is taken from #114
Collaborator

Should have a section explaining props. Right now you jump into an example "The Card function takes two props (parameters): { title, children }." but beginners might not know what props are.

Should have a section explaining props. Right now you jump into an example "The Card function takes two props (parameters): { title, children }." but beginners might not know what props are.
Collaborator

Review of the React wiki

I have reviewed the official React documentation and compared it with this React wiki

The current wiki is overall correct and provides a good understanding of the topics shown. However there are some areas missing that would make the wiki more complete. As mentioned the JSX section is currently not there and must be added. The wiki could also be improved by adding a section explain prop and state and maybe the difference between them. While props are used as examples it is not fully explained. Another important topic in react that is missing is event handling for example, "onClick".

Overall, good wiki but missing some areas such as, JSX, prop and state, event handling.

Review of the React wiki I have reviewed the official React documentation and compared it with this React wiki The current wiki is overall correct and provides a good understanding of the topics shown. However there are some areas missing that would make the wiki more complete. As mentioned the JSX section is currently not there and must be added. The wiki could also be improved by adding a section explain prop and state and maybe the difference between them. While props are used as examples it is not fully explained. Another important topic in react that is missing is event handling for example, "onClick". Overall, good wiki but missing some areas such as, JSX, prop and state, event handling.
Sign in to join this conversation.
No milestone
No project
4 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Andras/BoundlessFlowCampus2K#250
No description provided.