Giter VIP home page Giter VIP logo

error-derived-state's Introduction

- Código não otimizado

Error Derived State

- Código otimizado

Fixing Derived State

 

Error Derived State

Github top language Github language count Repository size Last Commit

About   |   Technologies   |   Requirements   |   Starting   |   License   |   Author


🎯 About

Um dos erros mais comuns no React (e você provavelmente já cometeu também) é a criação de estados derivados, que são estados criados a partir de outra informação já presente no componente.

Esses estados acabam causando renderizações desnecessárias, que podem ser substituídos facilmente por variáveis calculadas em tempo de execução.

/* . . . */

export function App() {
  const [repos, setRepos] = useState<Repo[]>([]);
  const [filteredRepos, setFilteredRepos] = useState<Repo[]>([]); // one state ( + )
  const [search, setSearch] = useState('');

  console.log('Render');

  useEffect(() => {
    fetch('https://api.github.com/users/wsasouza/repos')
      .then((response) => response.json())
      .then((data) => setRepos(data));
  }, []);

  useEffect(() => { // one useEffect ( + )
    if (search.length > 0)
      setFilteredRepos(repos.filter((repo) => repo.name.includes(search)));
  }, [search]);

  return (
    <div>
      <input
 /* . . . */

👆 Código não otimizado gerando renderizações desnecessárias.

/* . . . */

export function App() {
  const [repos, setRepos] = useState<Repo[]>([]);
  // removing unnecessary state ( - )
  const [search, setSearch] = useState('');

  console.log('Render');

  useEffect(() => {
    fetch('https://api.github.com/users/wsasouza/repos')
      .then((response) => response.json())
      .then((data) => setRepos(data));
  }, []);

  // Removing unnecessary useEffect ( - )

  const filteredRepos = search.length > 0 // ( + )
	? repos.filter(repo => repo.name.includes(search))
	: [];

  return (
    <div>
      <input
 /* . . . */

👆 O React só precisou renderizar esse componente novamente quando setSearch foi chamado dentro do input. O valor dos repositórios filtrados não precisam ficar dentro de um novo estado, pois eles podem ser calculados dentro de um componente como uma variável.

🚀 Technologies

The following tools were used in this project:

✅ Requirements

Before starting 🏁, you need to have Git and Node installed.

🏁 Starting

# Clone this project
$ git clone https://github.com/wsasouza/error-derived-state

# Access
$ cd error-derived-state

# Install dependencies
$ yarn

# Run the project
$ yarn start

# The server will initialize in the <http://localhost:3000>

📝 License

This project is under license from MIT. For more details, see the LICENSE file.

Made with ❤️ by Walter Santos de Andrade Souza

 

Back to top

error-derived-state's People

Contributors

wsasouza avatar

Watchers

 avatar

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.