开发者
🚀 30 React.js Interview Questions You Should Know Before Your Next Frontend Interview ⚛️
30 React.js Interview Questions You Should Know Before Your Next Frontend Interview ⚛️ Whether you're preparing for a frontend interview or simply want to brush up on your React.js knowledge , this guide covers 30 real-world, scenario-based React interview questions that interviewers frequently ask. The goal isn't just to memorize definitions. These questions are designed to help you understand how and when to apply React concepts in real-world applications . 📌 Bookmark this article and come back to it during your next interview preparation session. 📚 What We'll Cover In this guide, we'll explore questions around: Conditional rendering API calls and side effects Form validation Performance optimization State management Component re-rendering Keys and lists Dark mode Dynamic components useEffect vs useLayoutEffect Large-list optimization And much more... 1. How do you handle conditional rendering in React? Conditional rendering allows you to render different UI based on application state or conditions. You can use standard JavaScript techniques such as: if...else Ternary operators Logical && Example { isLoggedIn ? < Dashboard /> : < Login />} 💡 Interview Tip For simple conditions, a ternary operator or && is usually sufficient. For more complex conditions, consider moving the logic outside the JSX to keep the component readable. 2. You need to fetch API data when a component mounts. What's the best way to do it? 💡 Key Concept The typical approach is to perform the API request inside a useEffect hook when the component needs to fetch data after rendering. A common pattern is: useEffect (() => { // Fetch API data }, []); The empty dependency array indicates that the effect is intended to run after the initial render. Note: In modern React applications, the best approach can also depend on the framework or data-fetching library you're using. 3. How would you handle form validation in React? A common approach is to use controlled inputs and perform validation during even
AI 资讯
🤖 AI agents are becoming “digital employees”
SpaceXAI recently introduced Grok Bot, an always-on AI-agent service designed to work more like an autonomous teammate. The agents have their own cloud computer environment and can log into applications, websites and tools to perform multi-step tasks. They can also operate in parallel and coordinate with other agents. The product is entering a market that already includes competing agentic workplace products from OpenAI, Anthropic and Microsoft. Traditional chatbot: User ↓ Question ↓ LLM ↓ Answer And Now Agent: Goal ↓ LLM ↓ Plan ↓ Tool ↓ Observe ↓ Reason ↓ Tool ↓ Validate ↓ Continue ↓ Result * But there's a major problem : * Giving an AI agent access to: Email Slack GitHub CRM Cloud Browser Databases Internal documents creates a huge identity and security problem. An agent with permission to send an email or modify production infrastructure effectively becomes another privileged identity. About the Author -> I am Ashutosh Maurya , a Senior Full-Stack Developer ** with 6+ years of experience in high-performance UI development and the MERN stack. I specialize in building scalable architectures like Schooliko and **AI-integrated platforms . My goal is to bridge the gap between complex backend logic and seamless frontend experiences.
AI 资讯
Docker Compose Isn't What I Thought It Was
post 7: A practical guide to understanding Docker Compose—what it is, how it works, and the misconceptions that catch most beginners. You've mastered single containers. Now it's time to build a real application. A frontend. A backend. A database. A Redis cache. Suddenly you're juggling multiple docker run commands. Ports. Networks. Volumes. Environment variables. Chaos. Then someone says: "Just use Docker Compose." It works beautifully. But here's the twist most people never realize… Why Docker Compose Exists Imagine starting an application like this: Frontend Backend PostgreSQL Redis Running each container manually quickly becomes repetitive and error-prone. Docker Compose lets you describe your entire application in a single YAML file and start everything with one command. Instead of remembering dozens of commands, you define your infrastructure once. What Docker Compose Actually Is Docker Compose is not a container orchestrator . Docker Compose is a tool that reads your Compose YAML file and uses the Docker Engine to create and manage the resources defined in it.” Modern Docker uses Compose V2 , which runs as: docker compose instead of the older: docker-compose Compose runs only when you execute a command. It creates the required Docker resources, starts the containers, and then exits. This makes it ideal for development, testing, and single-host deployments , but it doesn't provide orchestration features like automatic scheduling, self-healing, or multi-node management. A Simple docker-compose.yml services : web : build : . ports : - " 8080:80" environment : - DB_HOST=db depends_on : - db db : image : postgres:15 volumes : - postgres_data:/var/lib/postgresql/data redis : image : redis:alpine volumes : postgres_data : YAML Quick Reference Key Purpose services Defines containers (web, db, redis) build Builds an image from a Dockerfile image Uses an existing image from a registry ports Maps host ports to container ports environment Sets environment variables depend
AI 资讯
How to Turn Latitude and Longitude into an Address with JavaScript
Sometimes you have GPS coordinates like: 40.7128, -74.0060 But coordinates alone are not very useful to most users. They usually want to know something much simpler: What place is this? The process of converting latitude and longitude into a human-readable address is called reverse geocoding . In this article, we'll build a simple reverse geocoding example with JavaScript. What Is Reverse Geocoding? Normal geocoding converts an address into coordinates: New York, NY ↓ 40.7128, -74.0060 Reverse geocoding does the opposite: 40.7128, -74.0060 ↓ New York, NY, United States This is useful for location tools, GPS applications, travel websites, delivery systems, photo location tools, and map interfaces. Reverse Geocoding with JavaScript For a simple example, we can use the OpenStreetMap Nominatim reverse geocoding endpoint. async function reverseGeocode ( lat , lon ) { const url = `https://nominatim.openstreetmap.org/reverse` + `?lat= ${ lat } &lon= ${ lon } &format=jsonv2` ; const response = await fetch ( url ); if ( ! response . ok ) { throw new Error ( " Reverse geocoding failed " ); } const data = await response . json (); return data ; } reverseGeocode ( 40.7128 , - 74.0060 ) . then ( data => { console . log ( data . display_name ); }) . catch ( error => { console . error ( error ); }); The returned data usually contains a readable location name together with structured address information. Display the Address on a Page We can turn the example into a small browser tool. <input id= "lat" placeholder= "Latitude" > <input id= "lon" placeholder= "Longitude" > <button onclick= "findAddress()" > Find Address </button> <p id= "result" ></p> <script> async function findAddress () { const lat = document . getElementById ( " lat " ). value ; const lon = document . getElementById ( " lon " ). value ; const result = document . getElementById ( " result " ); try { const url = `https://nominatim.openstreetmap.org/reverse` + `?lat= ${ lat } &lon= ${ lon } &format=jsonv2` ; const res
AI 资讯
A Security Fix Should Show Where the Attack Stopped
The concrete problem A security pull request can be green for the wrong reason. Unit tests may pass, the vulnerable endpoint may return a different status code, and a scanner may stop reporting the original finding. None of those results necessarily shows that the attacker lost the capability that mattered. The same identity might reach the sensitive action through another route, inherit a broader token, or trigger an equivalent workflow with slightly different input. This becomes especially uncomfortable when an automated tool proposes or reviews the fix. A plausible patch explanation is not behavioral evidence. The reviewer still needs to know which identity was used, which preconditions were established, which requests ran, where privilege was gained before the fix, and at which exact step the patched build denied it. Without that trace, “fixed” is partly an assertion about code rather than an observation of the attack path. The current signal On August 17, Wiz described a GitHub Actions script-injection flaw in a Snowflake repository. The vulnerable workflow change reached production on June 18 and Wiz reported exploiting it on June 23. The final squash commit credited Copilot Autofix as a co-author, while AI-assisted review did not flag the injection. Wiz later clarified that it could not determine whether the code change itself was AI-generated. That distinction matters: the lesson is about assurance around AI-assisted workflows, not proof that a model wrote the bug. The Hacker News discussion was active when RayTally captured it at 2026-08-18 00:33 UTC: 306 points, 123 comments, and rank 5. Those are historical attention numbers, not market validation. The useful engineering signal is narrower. Teams now have a concrete incident in which an apparently protective condition and an escaping routine still produced a reachable credential-exfiltration path. Bright STAR and StackHawk show that dynamic testing in CI is already real. Bright documents building and star
AI 资讯
7 MCP Tool-Schema Mistakes That Make AI Agents Less Reliable
AI agents can only use tools as reliably as those tools are described. That’s why I built ToolReady AI —a free tool that reviews MCP and AI-agent tool schemas, identifies reliability problems, and recommends specific fixes. A function might work perfectly when a developer calls it directly, yet still fail when an agent has to decide when to call it, which arguments to provide, and what values are safe. In many cases, the problem is not the underlying API. It is the tool schema placed between the API and the model. Here are seven issues worth checking before releasing an MCP or AI-agent tool. A description that is too vague Descriptions such as "Searches documents" do not give an agent enough routing context. The description should identify the supported content, expected result, important limits, and a clear use case. Better: «Search indexed support documents and return the most relevant text excerpts. Use this when answering questions about product setup or troubleshooting. Do not use it for account-specific or real-time billing information.» No boundary conditions A useful description should also explain when the tool should not be used. Exclusions help an agent distinguish similar tools and avoid calls that cannot succeed. Examples include: Do not use for personal account data. Do not use when the user requests current inventory. Do not use for destructive actions without confirmation. Undocumented inputs An input name such as "query", "id", or "limit" may seem obvious to its author, but the agent still has to guess the required meaning and format. Each property should explain: What the value represents The expected format A realistic example Any important constraints Missing required fields If the schema does not identify the minimum necessary inputs as required, an agent may send an empty or incomplete call that cannot produce a useful result. For example: { "type": "object", "properties": { "query": { "type": "string", "description": "Natural-language search q
AI 资讯
We Tested 4 Text-to-Speech Engines on 12,000 Live Healthcare Calls — Here's Which One Patients Actually Trust
Last quarter, we ran our production voice AI receptionist — Loquent — across four different TTS engines simultaneously, split-testing real patient calls at dental and healthcare clinics. The results surprised us: the most "natural sounding" engine in demos performed the worst with actual patients. Why We Ran This Test At Autor, we've been running Loquent in production for over a year now. It handles thousands of automated calls per month for healthcare and dental clinics across Canada — booking appointments, answering insurance questions, handling after-hours triage. The voice is the product. If patients don't trust the voice, they hang up, and the clinic loses a booking. When we first built Loquent, we picked our TTS engine the way most teams do: we generated a few sample clips, played them for ourselves, and went with the one that sounded best in a quiet office. That worked fine until we started digging into our call analytics and noticed something weird. Our completion rate — the percentage of calls where patients actually finished the full interaction instead of hanging up or asking for a human — was hovering around 74%. Good, but not great. We suspected the voice itself was part of the problem. So we designed a proper A/B test. Not a demo comparison. A production comparison on live calls. The Setup We tested four TTS engines across 12,247 calls over 8 weeks. Each engine handled roughly equal volume, randomly assigned at call start. All other variables stayed constant: same prompts, same Anthropic Claude backbone for conversation, same Twilio infrastructure, same clinics. The four engines: Engine A : ElevenLabs (Turbo v2.5) — our existing production engine Engine B : OpenAI TTS (tts-1-hd) — the model most teams default to Engine C : Deepgram Aura — optimized for real-time, low-latency use cases Engine D : A newer entrant we'd been evaluating (under NDA, so I can't name it) We measured five things: Completion rate — did the patient finish the full call flow? Time
开源项目
ARCLUX 🦖 —a codebase intelligence tools
Documentation OPEN SOURCE official documentation content, searchable and organized ...
AI 资讯
COSP: The Prompting Trick Where Your LLM Grades Its Own Homework
Hello, I'm Maneshwar. I'm building git-lrc, a Micro AI code reviewer that runs on every commit. It is...
开发者
🚀 SoloEngine v0.4.0 Release
🚀 SoloEngine v0.4.0 Release — Context Compaction, Browser/Terminal Panels, Token Statistics...
AI 资讯
Building Fault-Tolerant, Event-Driven Kafka Pipelines in Go: Reliable Reprocessing & Dead Letter Queues
A practical guide to building reliable event-driven systems in Go using Apache Kafka. Learn how to implement tiered retry strategies with delayed reprocessing, route permanently failed messages to dead letter queues in Golang with Sarama. Prerequisites What do you need to follow along? Working knowledge of Golang. Go & Docker installed on your PC. What is an Event-Driven Architecture? An Event-Driven Architecture (EDA) is a design approach where services communicate by producing and responding to events. Each service operates independently, producing or reacting to events as they happen. What are Events? An event is a record of something that has happened in a system, typically representing a state change or a significant action. An event contains data (payload) describing what happened. An example of an event could be: A user signing up for a service. A user placing an order in your system. Components of an Event-Driven Architecture To understand how events flow through a system, we need to know three key players: Event Producers : They are the sources of events. They generate and publish events like signup events, order placed events, etc. Producers generate events and transmit them to the rest of the system. They do not know who is listening for or handling the events. Event Brokers : They sit between producers and consumers, decoupling them so neither needs a direct connection to the other. Brokers receive event messages, maintain their chronological order, make them available for consumption, and route them to the right consumers. Apache Kafka is an example of an event broker, and it's the one we'll use throughout this guide. Event Consumers : They handle the processing tasks. They listen on event channels and react when an event they are subscribed to is published, then they process the event, which can include making API calls, updating a database, triggering other events, or logging information. The Complete Flow With those three pieces in place, the flow of
AI 资讯
Your backup is not a backup until you have restored it
This is an English write-up of a post from my Japanese dev diary. Original: https://saas-diary.com/tech-log/backup-restore-drill-automation/ For over a year, my backup job has reported success every single night. Green check, every day, no exceptions. Then I asked myself one question and went cold: "How many times have I actually restored from it?" Zero. Not once. "It was backed up" and "it can be restored" are different states My setup has two paths. One mirrors all source to a private repo. The other packs the things I can never recreate — notes, config, and Android signing keys — into an encrypted bundle and ships it to a private channel every night. Both were green every day. But green only proved the upload finished . It never proved the contents were right, or that the archive could even be opened. Within one month, I had two failures that stayed green the whole time. Failure 1. The collector for signing keys used three hardcoded paths. I kept shipping new apps, so the number of keys kept growing — but the collector didn't. By the time I noticed, 7 of 10 keys were missing from the backup . Five of those apps were live on the store. If my machine had died, I could never have shipped an update for them again. The backup reported success every night through all of it. Failure 2. The mirror push failed 7 days in a row (a large binary hit the host's file-size limit). But the script printed "✅ done" and returned exit code 0 even when one half failed. A failure that isn't visible isn't a failure — it's a time bomb. So I automated a restore drill Once a month, a job now does this: Rebuild the encrypted bundle (without shipping it) Actually decrypt it with the stored passphrase Extract it and count what's inside Check the mirror is not stalled (latest commit timestamp via API) Delete the scratch folder and the generated bundle The encryption is openssl-compatible AES-256-CBC with PBKDF2 (SHA-256, 100k iterations). I deliberately avoided depending on the openssl binary,
开发者
The same Rust gave two different answers, and neither matched JavaScript
This is a submission for DEV's Summer Bug Smash: Smash Stories powered by Sentry. Demo...
AI 资讯
I Ripped Out a Carousel Library. CSS Replaced It.
The bug ticket said "carousel feels broken on trackpad." It took me forty minutes to find the actual...
AI 资讯
Architecting a Low-Power Geofencing Engine: Lessons from Battery Optimization on Android
Opening hook The silence in the room was absolute, save for the rhythmic scratching of pens against paper during a final exam. I was three rows back, feeling confident, until my phone decided to vibrate against the wooden desk. It wasn't a subtle hum; it was a rhythmic, aggressive buzz that echoed like a snare drum in a cathedral. Every single head turned in my direction. I scrambled to silence the device, but in my panic, I fumbled the power button. That moment of pure, unadulterated embarrassment was the catalyst for everything I have built since. The problem We live in an age where our devices are supposed to be smart, yet they consistently fail at the most basic context-aware tasks. We have high-end processors, sophisticated neural engines, and sophisticated sensor arrays, but we still have to manually toggle a 'silent' switch before entering a meeting, a lecture, or a mosque. The friction isn't just the act of flipping a switch; it is the cognitive load of remembering to do it and, more importantly, remembering to turn it back on afterward. I spent months living with the anxiety of a phone that might ring at the worst possible time. I tried existing automation tools, but they were either bloated, relied on cloud-based tracking that hammered my battery, or lacked the granular control I needed for specific locations. Most apps that promised location-based sound management were either imprecise or drained my battery by keeping the GPS radio active around the clock. I didn't want a heavy-duty tracking app; I wanted a silent, background-native utility that respected the hardware constraints of the Android platform while solving the specific problem of environmental sound management. The technical decision / implementation When I started building Muffle, my primary constraint was the battery. Android users are rightfully protective of their background processes, and if my app showed up as a primary battery consumer in settings, it was effectively useless. I had to de
开发者
Understanding chmod Without Memorizing Numbers
How Linux file permissions actually work under the hood, why symbolic mode is your best friend, and how to stop blindly typing chmod 777. Every Linux engineer has been there. You write a brand-new bash script, try to run it from your terminal, and hit an immediate roadblock: $ ./backup.sh bash: ./backup.sh: Permission denied You open your search engine or ask a chat assistant for help. Within seconds, you find an answer that tells you to run: chmod 777 backup.sh You run the command, hit enter, and the script runs. Problem solved, right? Not quite. In fact, you just opened the digital front door of that file to every single user and background service on the entire operating system. When I started managing Linux servers years ago, permissions felt like a strange puzzle of three-digit math problems. People kept throwing numbers around: 755 for scripts, 644 for web pages, 600 for SSH keys, and 777 whenever something broke and nobody knew why. I memorized those numbers like cheat codes in a video game. But whenever I had to handle a real permission problem, like giving a development team write access to a shared log folder without letting them delete each other's files, memorized numbers fell apart. Here is the secret: you do not need to do binary math or memorize three-digit codes to master Linux permissions. Linux has a built-in, human-readable permission syntax called symbolic mode . Once you understand how Linux looks at files, who owns them, and what actions each permission controls, chmod becomes one of the most intuitive tools in your terminal. Let's break down how it all works step by step. 1. What chmod Actually Does The name chmod stands for change mode . In Unix and Linux systems, every single file and directory has a "mode". That mode determines who is allowed to read it, write to it, or run it. When you run chmod , you are simply updating those access bits inside the Linux filesystem inode. To see the current mode of your files, open any terminal and run ls
AI 资讯
Você criou uma tabela de tokens pra proteger PDF. O Laravel já fazia isso.
O contrato do cliente tá numa URL que qualquer um adivinha A tarefa parecia simples: o cliente precisa baixar a nota fiscal dele. Você salvou em storage/app/public/notas/ , rodou php artisan storage:link , mandou o link e foi feliz. https://app.com/storage/notas/nota-1042.pdf . Semanas depois cai a ficha. Aquele arquivo está aberto na internet . Sem login, sem nada. E o nome é sequencial: quem baixou a nota-1042.pdf só precisa de curiosidade e cinco segundos pra tentar a 1041 . E a 1040 . Então você faz a coisa certa: tira do disco público e cria um sistema pra controlar acesso. Tabela download_tokens , model, geração de UUID, coluna expires_at , controller que valida, e um comando no scheduler pra limpar os vencidos. Sessenta linhas depois, funciona. E aí alguém comenta no PR: "por que você não usou uma URL assinada?" O sistema que você não precisava construir // ❌ migration + model + controller + command. tudo isso pra um PDF. Schema :: create ( 'download_tokens' , function ( Blueprint $table ) { $table -> id (); $table -> uuid ( 'token' ) -> unique (); $table -> string ( 'path' ); $table -> foreignId ( 'user_id' ); $table -> timestamp ( 'expires_at' ); $table -> timestamps (); }); public function gerarLink ( NotaFiscal $nota ): string { $token = DownloadToken :: create ([ 'token' => Str :: uuid (), 'path' => $nota -> arquivo_path , 'user_id' => auth () -> id (), 'expires_at' => now () -> addMinutes ( 10 ), ]); return route ( 'download' , $token -> token ); } Não tem nada de errado tecnicamente. O problema é o custo: mais uma tabela crescendo pra sempre, mais um comando no scheduler, mais um caminho pra testar. E você vai manter isso enquanto o projeto existir. O Laravel resolve o mesmo problema com uma assinatura criptográfica na própria URL. Sem estado, sem tabela, sem limpeza. Como uma URL assinada funciona A ideia é bonita de simples: o Laravel monta a URL com os parâmetros que você quer, calcula um hash disso tudo usando a APP_KEY e cola o hash no final. /not
AI 资讯
Seu log tem 40 mil linhas e nenhuma resposta
"Deu erro ao salvar, umas duas da tarde" É a única informação que você tem. O cliente não lembra o que clicou, não tirou print e já fechou a aba. Você abre o laravel.log . Quarenta mil linhas no dia. Faz um grep por "erro". Aparecem 1.200 ocorrências, e a maioria é isso: [2026-08-14 14:03:11] production.INFO: entrou [2026-08-14 14:03:11] production.INFO: erro aqui [2026-08-14 14:03:12] production.INFO: passou [2026-08-14 14:03:12] production.ERROR: Erro ao salvar Erro ao salvar o quê ? De qual usuário? Qual pedido? Qual valor? Aquele entrou da linha de cima é do mesmo request ou de outro cliente que estava usando o sistema no mesmo segundo? Você tem log. Você não tem informação. São coisas diferentes. O problema não é a falta de log. É o excesso de log inútil. public function emitir ( Pedido $pedido ) { Log :: info ( 'entrou no emitir' ); try { $nota = $this -> sefaz -> emitir ( $pedido ); Log :: info ( 'emitiu' ); } catch ( Throwable $e ) { // parabéns, você registrou que algo deu errado em algum lugar 🎉 Log :: error ( 'Erro ao emitir nota' ); return back () -> withErrors ( 'Falha na emissão' ); } } Repara no que esse catch jogou no lixo: a mensagem da exceção, o stack trace, o ID do pedido, o CNPJ, o retorno da SEFAZ. Tudo estava ali, na mão, e foi substituído por uma frase genérica. E os Log::info('entrou') espalhados? Aquilo foi debug que virou permanente. Hoje eles só servem pra empurrar as linhas úteis pra fora da tela. Duas perguntas que todo log precisa responder Um log serve pra duas plateias: você, com sono, às 3h da manhã — e uma máquina , filtrando milhões de linhas. As duas querem a mesma coisa: O que aconteceu , numa mensagem que não muda nunca. Com quem aconteceu , em dados separados da mensagem. Essa separação é o pulo do gato. Repare na diferença: // ❌ mensagem única pra cada pedido. impossível agrupar ou contar. Log :: error ( "Falha ao emitir nota do pedido { $pedido -> id } do cliente { $cliente -> nome } " ); // ✅ mensagem estável + contexto est
AI 资讯
SpaceXAI Launches Grok Bot for Autonomous AI Agents
SpaceXAI has introduced Grok Bot, a system of persistent AI agents that operate on dedicated cloud computers and can interact with websites, applications, inboxes, and other tools. By Daniel Dominguez
开源项目
How canvases make agentic workflows visible, steerable, and cost-efficient
Chat is great for intent, but agent work gets lost in the scroll. Here is how I use canvases with my agentic workflows—and why your workflow also deserves a canvas. The post How canvases make agentic workflows visible, steerable, and cost-efficient appeared first on The GitHub Blog .