no-constructed-context-values

Try in Playground
react-best-practicesBest PracticeWarning

0

No tags

No CWE or CVE

This rule warns when you've set the value prop of a Context.Provider as a non-stable value (i.e. object identities).

Fixing your value prop by placing it higher in a useMemo or useCallback hook can save you unnecessary re-renders.

ESLint has a similar rule react/jsx-no-constructed-context-values

Ast Rule: html element


no-constructed-context-values

How to write a rule
function visit(node, filename, code) {
  if (!node || !node.tag || !node.attributes) return;

  // check if there's a value prop
  const valueProp = node.attributes.find(a => a.name?.value === "value")
  if (!valueProp) return;

  // check if there's a `.Provider` in the element name
  if (!node.tag.value?.includes(".Provider")) return;

  // check if the value prop is reference or not
  if (!valueProp.value?.elements[0]?.elements) return;

  const error = buildError(
    valueProp.start.line,
    valueProp.start.col,
    valueProp.end.line,
    valueProp.end.col,
    `This context value prop changes every render. Consider wrapping the value in a useMemo/useCallback hook.`,
    "WARNING",
    "BEST_PRACTICE"
  )

  addError(error)
}

incorrect.jsx

Expected test result: has error

Incorrectly setting a context value prop

return (
  <SomeContext.Provider value={{foo: 'bar'}}>
    {children}
	</SomeContext.Provider>
)

correct.jsx

Expected test result: no error

Correctly setting a context value prop

const foo = useMemo(() => ({ foo: 'bar' }), []);

return (
  <SomeContext.Provider value={foo}>
        {children}
	</SomeContext.Provider>
)
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.